Search code examples
javascriptgoogle-chromegoogle-chrome-extensiongoogle-analyticsuniversal-analytics

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


I use analytics in my chrome extension like this

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');

with all the necessary permissions in manifest.json

Everything works as expected , except the cases where there is not internet at the start of the extension. In cases like these,the events are not sent to server as analytics.js is not loaded. This leads to loss of events until the next chrome restart with successful internet connection.

Is there a workaround to this.


Solution

  • Found an elegant way of doing this

    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