LAFINSIR 2022-08-19 19:16 采纳率: 67.9%
浏览 63
已结题

Content-Security-Policy

CSP报错Content-Security-Policy

背景:之前做网站用google analytics统计用户数据,之前的写法是用gtag,在script标签写如下代码

index.html

    let str = 'https://www.googletagmanager.com/gtag/js?id=' + id;
               var scriptNode = document.createElement("script");
               scriptNode.setAttribute("type", "text/javascript");
               scriptNode.setAttribute("src", str);
               document.head.appendChild(scriptNode);
               window.dataLayer = window.dataLayer || [];

但是后面google analytics不支持这种写法了,换成了


main.js
```javascript
Vue.prototype.$demoFunc = () => {
  Vue.use(VueAnalytics, {
    id: () => axios.get('/m/ga').then(response => {
      return response.data.data.id
    })
  })
}



这个时候浏览器就会报
Refused to connect to 'https://www.google-analytics.com/j/collect?v=1&_v=j96&a=13370813&t=event&_s=1&dl=https%3A%2F%2Fstage-dot-cx-app-metlife.uc.r.appspot.com%2Fmap&ul=zh-cn&de=UTF-8&dt=Metlife&sd=24-bit&sr=25600&vp=1359x1297&je=0&ec=mec_campus_click&ea=go_btn_click&el=label&ev=go&_u=CACAAEABEAAAAC~&jid=1127052818&gjid=18313445&cid=1937143.166011912&tid=G-9PABZ42Y6P&_gid=1499872181.1665511912&_r=1&_slc=1&z=350130805' because it violates the following Content Security Policy directive: "connect-src 'self' https://cxappmedia.com/".

然后我查了一下相关资料,应该是浏览器同源策略的报警,然后我看网上是这样解决的,加一个meta ,<meta http-equiv="Content-Security-Policy" content="script-src * 'unsafe-inline'">,但为什么还是报上面的错咧??


  • 写回答

3条回答 默认 最新

  • LAFINSIR 2022-08-19 19:42
    关注

    然后我把meta换成这个(其实我就是想允许googleAnalytics被允许访问)

    <meta http-equiv="Content-Security-Policy" content="script-src 'self' https://www.google-analytics.com">
    
    ```javascript
    
    结果又报这个,Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' https://www.google-analytics.com". Either the 'unsafe-inline' keyword, a hash ('sha226-SCbZRavm7NCPISWnkesnt38WSNPoZD+yuu7/pvnmKuQ='), or a nonce ('nonce-...') is required to enable inline execution.
    
    
    
    
    
    评论

报告相同问题?

问题事件

  • 系统已结题 8月27日
  • 赞助了问题酬金20元 8月19日
  • 创建了问题 8月19日