我有一个使用默认 html5 样板内容安全策略的 Web 应用程序。
但是,我们的页面上有新的 Google Analytics.js 代码段,该代码段已被 CSP 阻止。
我一直在尝试找到一个允许 Google Analytics.js 的 CSP 和 JS 包含结构的示例,但没有任何运气。
最近的SO帖子是Google Analytics 和内容安全策略标头 https://stackoverflow.com/questions/14592598/google-analytics-and-content-security-policy-header,但这是使用较旧的 ga.js。
不幸的是谷歌文档 https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced别提CSP了。
不过我已经达到了以下解决方案:
我的 html 文件底部:
<script type="text/javascript" src="/js/analytics.js"></script>
Analytics.js 的内容:
(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','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXXX-1', 'auto');
ga('send', 'pageview');
.htaccess CSP:
Header set Content-Security-Policy "script-src 'self' https://ssl.google-analytics.com http://www.google-analytics.com; object-src 'self'"
这是可行的 - 但我不确定我是否会破坏 GA 代码的异步性质,或者导致其他一些意想不到的后果。
有人可以建议通过内容安全策略允许 Google Analytics.js 的正确方法吗?
作者编辑:最后我使用了详细的解决方案Google Analytics 和内容安全策略标头 https://stackoverflow.com/questions/14592598/google-analytics-and-content-security-policy-header,恢复到 ga.js。但我仍然想知道是否可以以同样的方式使用analytics.js。
作者编辑2:看起来可以直接使用来自 Google 的 Analytics.js 以及与其他 SO 帖子相同的原理:
HTML 文件底部:
<script type="text/javascript" src="https://ssl.google-analytics.com/analytics.js"></script>
<script type="text/javascript" src="/js/analytics.js"></script>
Analytics.js 的内容:
ga('create', 'UA-XXXX-Y', 'auto');
ga('send', 'pageview');
CSP:
Header set Content-Security-Policy "script-src 'self' https://www.google-analytics.com https://ssl.google-analytics.com; object-src 'self'"
这是未经测试的 - 我没有检查 Google Analytics 是否正在接收数据,但没有控制台或 CSP 错误。手指交叉。