将Google Analytics(分析)添加到Chrome扩展程序

问题描述:

为了将Google Analytics(分析)添加到chrome扩展程序中,官方文档提供以下代码段:

In order to add google analytics to a chrome extension the official docs provide the following snippet:

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); })();

但是Google还建议从ga.js迁移到analytics.js .

But google also recommends to migrate from ga.js to analytics.js.

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

ga.js is a legacy library. If you are starting a new implementation, we recommend you use the latest version of this library, analytics.js. For existing implementations, learn how to migrate from ga.js to analytics.js.

在认真遵循迁移指南并进行升级后,具有新脚本(从https://ssl.google-analytics.com/ga.jshttps://www.google-analytics.com/analytics.js)的内容安全策略,它根本没有用,没有显示任何错误消息.

After following carefully the migration guide and upgrading the content security policy with the new script ( from https://ssl.google-analytics.com/ga.js to https://www.google-analytics.com/analytics.js ), it simply didn't work, without showing any error message.

欢迎任何建议

我的解决方案基于官方文档:

My solution is based on the official docs: 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