0

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.

Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34
  • @wOxxOm: you have closed this question, but the solutions that are given in the other answer don't work (at least for me). When I tried solution 0, my background script didn't do anything (but did register), in solution 1 the forever ports didn't work, and I don't want a dedicated tab either (solution 2). Maybe those were for manifest v2? They didn't really help me in this case. – Lakshya Raj Jun 30 '21 at 17:08
  • Every solution was tested (also by other people) and works in a ManifestV3 extension. – wOxxOm Jun 30 '21 at 17:09
  • @wOxxOm: Hmmm... seems like I'll have to find out how to make it work. Thanks for the help anyways. I think I'll try the forever ports, maybe I did something to it that made it stop working (like missing permission, not working with existing code, etc.) – Lakshya Raj Jun 30 '21 at 17:11
  • @LakshyaRaj have you been able to find any solution of the problem so far? – user1635430 Feb 15 '22 at 19:54
  • @user1635430: I did not. You might want to try the solutions in the "duplicate" suggestion. They didn't work for me, but maybe mine is just an exception. (Also sorry for the late response) – Lakshya Raj Mar 18 '22 at 03:49

0 Answers0