Search code examples
javascriptfirefox-addon

How does the "tabs.onUpdated" for Firefox Addons work?


I am playing around with the Firefox Addons, so it's mostly new to me. In addition, I don't have much JS knowledge. So on the Docs (https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/onUpdated) I found the 'tabs.onUpdated" Event and it would fit my need's perfectly (I need a event that runs a function if a tab with a specific url changes url). So I copied the examples and read me through the page but I couldn't get it working. Can somebody help me?

Thanks Akira


Code:

manifest.json:

{

  "manifest_version": 2,
  "name": "Testing Add-on",
  "version": "1.0",

  "description": "Test Add-on",

  "icons": {
    "48": "icons/border-48.png"
  },

  "content_scripts": [
    {
      "matches": ["*://developer.mozilla.org/*"],
      "js": ["content_script.js"]
    }
  ],

  "permissions": ["tabs", "<all_urls>"]
}

content_script.js: (just to test if script works)

console.log("Before");
browser.tabs.onUpdated.addListener((tabId, changed) => {
    if (changed.url) {
        console.log("True");
    }
})
console.log("After");

Solution

  • thanks for adding your manifest.json. In the browser console (the one you open with Ctrl+Shift+J or with web-ext run --bc) you can see the following error message:

    TypeError: browser.tabs is undefined

    This is because you are using browser.tabs in your content script, whereas you should use it in your background script.

    Add the following to your manifest file:

        "background": {
            "scripts": ["background_script.js"]
        }
    

    -> where the background_script.js has the content your content_script.js has. Leave your content script empty for now. This is the script that will be injected into pages that match given URL pattern.

    You could write something like the following into your content_script.js (just for testing): document.body.style.border = '5px solid red';

    True (from the onUpdated handler in your background script) will be printed to the browser console (not the developer tools console!) whenever the URL of that tab changes. Pages that match your URL pattern will show a red border;)