Context menus do not work on Firefox extension

I am trying to add a context menu to my Firefox add-on using the WebExtensions API. I need a background script to listen for a click on a 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);
});

A menu item is created, but messages are never displayed (I check both the Web and the Browser Console). Since the click event does not work, the message is also not sent.

I am following this example from MDN, which does not work. It also creates menu items, but they don’t do anything, which makes me think that something has changed in the API and MDN, and have not bothered to update the documentation.

Any ideas? Thank.

+4
1

:

Exit Browser Console

, :

:
: sendMessage(), , . , tabs.Tab , , . :

function sendMessage(info, tab) {
    chrome.tabs.sendMessage(tab.id, "Test message from background script.");
}

, , , tabs.Tab, .

+1

All Articles