In Manifest v2, you could just add "persistent": true
to the manifest.json
like this:
{
...
"background": {
"scripts": ["background.js"],
"persistent": true
},
...
}
Normally, it is said to use persistent: false, but right now I need my script to be persistent, without waiting for any events. I tried searching but it looks like they removed the persistent key and now I need to make my script "event based".
Trying to hack through, I opened a port like this:
// content script
var port=browser.runtime.connect();
port.onMessage.addListener(function(msg){
if(msg===0)port.postMessage(1);
});
setInterval(function(){
port.postMessage(Math.random());
},1000);
// background script
browser.runtime.onConnect.addListener(function(port){
port.onMessage.addListener(function(msg){
if(msg===1)port.postMessage(Math.random());
});
setInterval(function(){
port.postMessage(Math.random());
},1000);
});
Side note: I am using browser
instead of chrome
to make my extension usable across browsers (using a check, I set browser
to the current browser, but that's off topic)
But even with this port that keeps communicating, I see that my background script becomes inactive. Is there any working method to keep a background script active?
Other information: The reason I need to keep my background script going is because it uses captureVisibleTab
every second, but when it goes inactive, then it stops taking the screenshots. I want it to keep going forever, and that's why I want the script to be persistent.