Context menus not working firefox add-on WebExtensions

I’m trying to add a context menu to my firefox add-on using the WebExtensions API. I need the background script to listen to a click on the menu item and send a message to the content script. This is what I have:

manifest.json

{
  "manifest_version": 2,
  "name": "MyExt",
  "version": "0.0.1",

  "description": "Test extension",
  "icons": {
    "48": "icons/icon-48.png"
  },

  "applications": {
    "gecko": {
      "id": "myext@local",
      "strict_min_version": "45.0"
    }
  },

  "permissions": ["contextMenus"],

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

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content-script.js"]
    }
  ]
}

background-scripts.js

chrome.contextMenus.create({
    id: "clickme",
    title: "Click me!",
    contexts: ["all"]
});

browser.contextMenus.onClicked.addListener(function(info, tab) {
    console.log("Hello World!");
    sendMessage(info, tab);
});

function sendMessage(info, tab) {
    chrome.tabs.query(
        {active: true, currentWindow: true }, 
        function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, "Test message from background script.");
        }
    );
}

content-script.js

browser.runtime.onMessage.addListener(function(msg) {
    console.log(msg);
});

The menu item is being created, but the messages are never displayed (I’m checking both the Web and Browser Console). Since the click event is not working, the message is not sent either.

I’m following this example from MDN, which does not work. It also creates the menu items, but they do nothing, which makes me think that something changed in the API and MDN didn’t bother to update the documentation.

Any ideas? Thanks.

contextMenus is not supported until Firefox 48, as the documentation states: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/contextMenus#Browser_compatibility.

Your example worked for me in Developer Edition.

1 Like

This was exactly the problem. I assumed I had the latest version, but failed to notice that Firefox 48 is still in beta. Silly mistake. Thank you.