Search code examples
javascriptgoogle-chrome-extensionfirefox-addonbrowser-extension

Content script unloads when page is not visited for a long time


I'm working on a browser extension that needs to be constantly running, even after an automatic refresh in the background. The problem is, that the page randomly automatically unloads and the script just shuts off. I need to find a way to keep the content script on at all times. Here's part of the code:

// content.js:
    function run(fn) {
      if(typeof(Worker) !== "undefined") {
        if(typeof(w) == "undefined") {
          w = new Worker(URL.createObjectURL(new Blob(['('+fn+')()'])));
        }
        w.onmessage = function(event) {
          if (isNaN(grabbedmin) && ID) {
            bump() // Note: the bump function refreshes in the page.
            w.terminate();
          }
          if ($("[href='/server/bump/" + ID + "']").text().includes("Bump")) {
            bump()
            w.terminate();
          }
          document.getElementById("bumpcount").innerHTML = "Autobumper Enabled: " + getCurrentTimestamp();
          if (numberwow == grabbedmin) {
            bump()
            w.terminate();
          }
        };
      }
    }

The code above basically gets run every minute by this worker:

// content.js:
    const worker = run(function() {

      var i = 0;

      function timedCount() {
        i = i + 1;
        postMessage(i);
        setTimeout(function(){timedCount()},1000);
      }

      timedCount();
    });

Is there a way for background.js to detect that content.js is not running (or that the page is unloaded) when it should be and then reload it?

Note: You can find the script here: https://github.com/Theblockbuster1/disboard-auto-bump


Solution

  • After looking through the docs and looking at examples, I put this together:

    chrome.tabs.query({
      url: ["*://disboard.org/*dashboard/servers", "*://disboard.org/*dashboard/servers/"] // finds matching tabs
    }, function(tabs) {
      tabs.forEach(tab => {
        chrome.tabs.update(tab.id,{autoDiscardable:false});
      });
    });
    
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
      // checks if the browser automatically re-enabled autoDiscarding and disables it
      if (changeInfo.autoDiscardable == true) chrome.tabs.update(tabId,{autoDiscardable:false});
    });