Background script just working once

Hello, I am trying to make a small add-on for kiosks-like systems browser based.
My project is based in rural areas, so at times the network get unstable.

Basically it should detect if an error has happened (associated to network availability: timeout, wifi failed), wait a little time, and try to reload again. Until it succeeds.

I have followed the guides, and checked that at least the first time, it detects the failure. But after that, the trigger won’t activate again.

What am I doing wrong? How should I do it? (I accept more ideas and approaches)

manifest.json

{
  "manifest_version": 2,
  "name": "ElEspia",
  "version": "0.0.1",
  "browser_specific_settings": {
    "firefox": {
      "id": "undisclosed@undisclosed.org"
    }
  },
 
  "description": "Watchdog for kiosk-like systems browser based",

  "icons": {
    "48": "icons/icon.png"
  },

  "permissions": ["webNavigation"],

  "background": {
    "scripts": ["watchdog.js"],
    "persistent": true
  }
}

watchdog.js

async function logOnErrorOccurred(details) {
  console.log(`onErrorOccurred: ${details.url}`);
  console.log(details.error);
  await sleep(30000); // 10 s
  window.location.reload(true); // true make it reload from the server, false from caché
}

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

browser.webNavigation.onErrorOccurred.addListener(logOnErrorOccurred);

Also after a few tries, i get the error: “TypeError: can’t access dead object” that points to the line-> "if (!window || window.closed) … in webconsole.js

Your watchdog.js is running as a background script, but then you are trying to reload it? That doesn’t look good.

Make sure you understand the anatomy of Web extensions, especially background scripts:

If you want to reload a page in a tab where loading failed, you need to use different approach.
First you need to find out which tab failed loading (your browser.webNavigation.onErrorOccurred gives you tabId) and then reload it using browser.tabs.reload.

2 Likes

Thank you very much Juraj. You pointed me to the solution.

I really much appreciated.