Search code examples
google-chrome-extensioncross-browserfirefox-addonfirefox-addon-webextensionsbrowser-extension

Why is the background script not loading on Firefox add-on (works on Chrome)?


I'm developing a cross-browser extension which works in Chrome but not in Firefox - the background script is not loading.

I tried console.log in background.js and sending a message to the content script and logging message there.

background.js

browser.action.onClicked.addListener(async function (tab) {
   console.log("clicked on extension icon");
   browser.tabs.sendMessage(tab.id, { text: "toggle_overlay" })
      
});

js/content.js

...

browser.runtime.onMessage.addListener(function (msg, sender, sendResponse) {

   console.log("message received", msg)
   
});

Content script works as expected on all code that's not depended on background.js

Folder structure

enter image description here

manifest.json (had to downgrade to v2 because Firefox doesn't support v3 yet)

{
  "name": "Dev Mode",
  "description": "Dev Mode",
  "version": "0.0.1",
  "manifest_version": 2,
  "icons": {
    "16": "./imgs/icon-16-dark.png",
    "48": "./imgs/icon-48.png",
    "128": "./imgs/icon-128.png"
  },
  "permissions": [
    "activeTab",
    "contextMenus",
    "bookmarks",
    "scripting",
    "storage",
    "<all_urls>"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false // <-- also tried without, same result - background script doesn't lod
  },  
  
  "browser_action": {
    "default_icon": "./imgs/icon-16-dark.png",
    "default_title": "Default Title"
  },
  "commands": {
    "save-page": {
      "suggested_key": {
        "default": "Ctrl+Shift+S",
        "mac": "Command+Shift+S"
      },
      "description": "some description"
    }
  },
  "content_security_policy": "script-src 'self'; object-src 'self'; sandbox allow-scripts; script-src 'self' https://apis.google.com https://www.gstatic.com https://www.googleapis.com https://securetoken.googleapis.com; object-src 'self'",
  "web_accessible_resources": [ "imgs/*.png",  "overlay.html"],
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "/js/content.js"
      ],
      "run_at": "document_end",
      "all_frames": false
    }
  ]
}

I'm testing the Firefox extension with web-ext run to test the extension locally.


Solution

  • The correct API for this in Manifest v2 is browserAction instead of action that is only available in MV3.

    So to fix it, in your background.js, switch to

    browser.browserAction.onClicked.addListener