启用Chrome扩展分析时,互联网是不可用的扩展
我使用分析在我的浏览器扩展程序是这样开始启用Chrome扩展分析时,互联网是不可用的扩展
background.js
// Standard Google Universal Analytics code
(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-YY', 'auto');
ga('set', 'checkProtocolTask', function(){}); // Removes failing protocol
ga('require', 'displayfeatures');
了所有必要的权限manifest.json中
除了在扩展开始时没有互联网的情况外,一切都按预期工作。在这些情况下,事件不会作为analytics.js发送到服务器。这会导致事件丢失,直到下一次成功连接Internet的Chrome重启。
是否有解决这个问题的方法。
找到这样
function loadAnalyticsScript() {
// The standard Google Universal Analytics code
(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'); // Note: https protocol here
}
var analyticsLoaded = false; // initialise
loadAnalyticsScript();
/************Detect if analytics script has loaded **********/
// Method 1 src:https://davidsimpson.me/2014/05/27/add-googles-universal-analytics-tracking-chrome-extension/#comment-190946
ga(function(){
// This function will be triggered when GA is successfully loaded for the first time.
console.log(' +++ Google Analytics has loaded');
analyticsLoaded = true;
});
// Alternative Method 2 src:https://www.domsammut.com/code/workaround-for-when-the-hitcallback-function-does-not-receive-a-response-analytics-js
if (ga.hasOwnProperty('loaded') && ga.loaded === true) {
console.log(' +++ Google Analytics has loaded');
analyticsLoaded = true;
}
/*************************************************/
// All the events tracking goes here
ga('create', 'UA-XXXXX-YY', 'auto');
ga('set', 'checkProtocolTask', function(){}); // Removes failing protocol check. @see: http://stackoverflow.com/a/22152353/1958200
ga('require', 'displayfeatures');
ga('send', 'pageview', '/options.html');
// Test to see if it's loaded yet.
var gaLoadTimer = setInterval(function(){
if (analyticsLoaded === false) {
console.log("Retrying for GA script");
loadAnalyticsScript(); //try again
}
else{
clearInterval(gaLoadTimer);
}
}, 20000); // every 20s
使用XMLHttpRequest
来测试https://www.google-analytics.com/analytics.js
是否可到达。如果不是,请使用chrome.alarms API(最好)或setInterval
创建一个计时器,它将重复此测试。一旦网站可以访问,初始化GA。
致谢优雅的方式为answer.Also发现的替代,以检查的analytics.js是否加载https://www.domsammut.com/code/workaround-for-当hitcallback-function-does-not-receive-a-response-analytics-js – mallik1055
@ mallik1055时,其他方法值得作为与源文章链接的答案呈现。您是否愿意添加它,甚至可以选择作为解决方案? – wOxxOm
注意使用20s'setInterval',如果你使用Event页面('“persistent”:false'),它会失败。 – Xan