Search code examples
javascriptfirefoxfirefox-addon

browser.tabs is undefined in firefox extension


Here is my manifest.json file:

{
  "manifest_version": 2,

  "permissions": ["tabs", "storage", "webRequest", "<all_urls>"],

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["assets/js/jquery-3.3.1.min.js", "blocker.js"]
    }
  ],

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

  "options_ui": {
    "page": "background-page.html",
    "browser_style": true
  }
}

and my blocker.js file:

function cleanPage(tabId, changeInfo, tabInfo) {
  console.log("I am in cleanPage");
}

try {
  console.log("browser : ");
  console.log(browser);
  console.log("browser.tabs : " + browser.tabs);

  browser.tabs.onUpdated.addListener(cleanPage);

} catch(err) {
  console.log("err : ", err);
}

And I get this error:

browser.tabs : undefined blocker.js:114:3
err :  TypeError: "browser.tabs is undefined"

My setup:
- Mozilla Firefox 65.0.1
- Ubuntu 18.04

I don't really understand this error, since I'm doing exactly what is written in the Mozilla Tutorial. Does anyone know why this error does appear?


Solution

  • My blocker.js file was in the content_scripts. I moved it to the background_scripts and it worked.

    Only the files from the background_scripts can access the browser.tabs API.

    My new manifest.json file:

    {
      "manifest_version": 2,
    
      "permissions": ["tabs", "storage", "webRequest", "<all_urls>"],
    
      "content_scripts": [
        {
          "matches": ["<all_urls>"],
          "js": []
        }
      ],
    
      "background": {
        "scripts": ["assets/js/jquery-3.3.1.min.js", "background.js", "blocker.js"]
      },
    
      "options_ui": {
        "page": "background-page.html",
        "browser_style": true
      }
    }