将 Google Analytics 添加到 Chrome 扩展程序

loc*_*ton 12 javascript google-analytics google-chrome-extension

为了将谷歌分析添加到 chrome 扩展,官方文档提供了以下代码段:

var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview']);

(function() {   var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;   ga.src = 'https://ssl.google-analytics.com/ga.js';   var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })();
Run Code Online (Sandbox Code Playgroud)

但是 google 也建议从 ga.js 迁移到 analytics.js

ga.js 是一个遗留库。如果您要开始新的实施,我们建议您使用此库的最新版本 analytics.js。对于现有实现,了解如何从 ga.js 迁移到 analytics.js。

在仔细遵循迁移指南并使用新脚本( from https://ssl.google-analytics.com/ga.jsto https://www.google-analytics.com/analytics.js)升级内容安全策略后,它根本不起作用,没有显示任何错误消息。

欢迎任何建议,

Del*_*iaz 8

我的解决方案基于官方文档:https : //developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference

但稍作修改:

(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-XXXXX-Y', 'auto');

// Modifications: 
ga('set', 'checkProtocolTask', null); // Disables file protocol checking.
ga('send', 'pageview', '/popup'); // Set page, avoiding rejection due to chrome-extension protocol 
Run Code Online (Sandbox Code Playgroud)


小智 -1

尝试使用以下代码片段进行异步跟踪,这里是文档

<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-XXXXX-Y', 'auto');
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
Run Code Online (Sandbox Code Playgroud)