CSP正在阻止Google Analytics代码

时间:2016-04-12 21:33:38

标签: google-analytics google-analytics-api

我有一个简单的localhost网站来测试Google Analytics,但每次我访问该网站并查看日志时,我都会看到CSP阻止了JavaScript代码。

这是脚本:

<script type="text/javascript">

    (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
        }, i[r].l = 1 * new Date(); a = s.createElement(o),
        m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
    })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

    ga('create', 'UA-12345678-1', 'auto', { 'siteSpeedSampleRate': 100 });
    ga('send', 'pageview');

    ga('create', 'UA-87654321-1', 'auto', 'clientTracker', { 'siteSpeedSampleRate': 100 });
    ga('clientTracker.send', 'pageview');

</script>

以下是CSP内容:

  <httpProtocol>
      <customHeaders>
        <add name="Content-Security-Policy" value="default-src 'self'; script-src 'self' https://www.google-analytics.com https://ssl.google-analytics.com; style-src 'self' 'unsafe-inline'; img-src 'self' http://www.google-analytics.com https://ssl.google-analytics.com; object-src 'none'; media-src 'none'; frame-src 'none' "/>
      </customHeaders>
  </httpProtocol>

最后,这里是错误的屏幕截图: enter image description here

注意:我确实遇到了一些帖子(herehere),虽然我发现其中有一些相似之处,但我找不到解决方案对我有用(或者也许我做错了,如果有的话,请指出)。

2 个答案:

答案 0 :(得分:0)

https://www.google…/etc更改为//www.google… 我相信你的问题是你的本地主机不安全并导致问题。

删除协议(以//开头)允许浏览器根据请求站点确定自己的协议(http | https)。

答案 1 :(得分:-3)

终于搞定了。 CSP内容:

<add name="Content-Security-Policy" value="default-src 'self'; script-src 'self' 'unsafe-inline' www.google-analytics.com; style-src 'self' 'unsafe-inline'; img-src * data:; object-src 'none'; media-src 'none'; frame-src 'none' "/>