运行 Google Chrome 扩展后台脚本中的分析请求

Run Google Analytics Request in a Chrome Extension Background Script

这里我有这段代码,它运行对 google 分析的请求(我检查过,该部分在弹出脚本中工作)并且我希望它发送每日“订单”可以这么说让我知道我每天安装了多少次。

出于测试目的,我已将间隔设置为 5 秒,但这似乎不起作用。

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*/

关于后台脚本,我是否遗漏了什么?请求似乎没有发送,我该如何解决?

你忽略了他们没有持续执行的事实。请参阅 Migrating to Service Workers 文档:

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.

在这里实现你想要的东西的惯用方法是使用 chrome.alarms API,link.

也对此进行了讨论

请注意,“武装”警报不会在扩展程序完全重启后继续存在(例如,如果浏览器重新启动),因此您可能应该保存上次警报代码成功执行的时间,并检查是否需要发送beacon / 你什么时候应该在扩展开始时安排一个新的警报(例如通过 chrome.runtime.onStartup)。