Search code examples
javascriptgoogle-chrome-extensionbackground-process

Run Google Analytics Request in a Chrome Extension Background Script


Here I have this code, which runs a request to google analytics (I checked, that part works in a popup script) and I would like it to send a daily "order" so to speak to let me know how many daily uses I have installed.

I have set the interval to 5 seconds for testing purposes, but this does not seem to work anyway.

function doSomething() {

 chrome.storage.sync.get('session', function(result){
var val = result.session;
 var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://bat.global.cf:8000/checkok.html?rando="+val);
xhttp.send();
xhttp.open("GET", "https://www.google-analytics.com/collect?v=1&tid=UA-232507651-1&cid="+val+"&t=pageview&dp=%2Fdaily24hCheck");
xhttp.send();
 });

}

setInterval(doSomething, 5000); // Time in milliseconds


/*Anonymous anylitics code for a background script  end*/

Is there something I am missing about background scripts? The request does not seem to be sent, how can I fix this?


Solution

  • You are missing the fact that they are not persistently executing. See the Migrating to Service Workers documentation:

    It's common for web developers to perform delayed or periodic operations using the setTimeout or setInterval methods. These APIs can fail in service workers, though, because the scheduler will cancel the timers when the service worker is terminated.

    The idiomatic way to achieve what you want here is to use the chrome.alarms API, which is also discussed at that link.

    Note that "armed" alarms won't survive a full extension restart (e.g. if the browser is restarted), so you probably should save the last time your alarm code has successfully executed and check if you need to send a beacon / when should you schedule a new alarm on extension start (e.g. through chrome.runtime.onStartup).