当扩展开始时互联网不可用时,在 chrome 扩展中启用分析

Enable analytics in chrome extension when internet is not available at start of extension

我在我的 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 未加载。这会导致事件丢失,直到下一次 chrome 重新启动并成功连接互联网。

是否有解决方法。

使用XMLHttpRequest测试https://www.google-analytics.com/analytics.js是否可达。如果不是,请使用 chrome.alarms API(最好)或 setInterval 创建一个计时器,这将重复此测试。网站可访问后,初始化 GA。

找到了一种优雅的方法

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: 
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