Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

javascript - Add Google Analytics to a Chrome Extension

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

But google also recommends to migrate from ga.js to 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.

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.

Any suggestion welcome,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

My solution is based on the official docs: https://developers.google.com/analytics/devguides/collection/analyticsjs/tracking-snippet-reference

But slightly modified:

(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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...