I am writing a first test of a firefox extension. I am using the following websites as assistance:
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Your_first_WebExtension
https://github.com/mdn/webextensions-examples/blob/main/menu-demo/background.js
Here is my code:
mainfest.json
{
"manifest_version":2,
"version":"1.0",
"name":"Test",
"content_scripts":[
{
"matches":["<all_urls>"],
"js":["main.js"]
}
],
"permissions":["contextMenus"]
}
main.js
alert("test");
function onError(error) {
alert(error);
}
browser.contextMenus.create(
{
id: "AlertTest",
title: "Test2",
contexts: ["all"],
},
onCreated,
);
alert("Test 2");
browser.contextMenus.onClicked.addListener((info, tab) => {
switch (info.menuItemId) {
case "AlertTest":
console.log(info.selectionText);
alert("The test extension is up and running");
break;
}
});
The extension does load, but i never get to alert("Test 2");. In addition the console says "TypeError: browser.contextMenus is undefined". Please let me know what I’m doing wrong.
Edit: Getting closer, but context menu addition still isn’t showing up. Current code…
manifest.json
{
"manifest_version": 2,
"version": "1.0",
"name": "Test",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"permissions": [
"contextMenus",
"activeTab"
]
}
background.js
function onError(error) {
console.log(error);
}
browser.contextMenus.create(
{
id: "AlertTest",
title: "Test2",
contexts: ["all"],
},
onCreated,
);
browser.contextMenus.onClicked.addListener((info, tab) => {
switch (info.menuItemId) {
case "AlertTest":
console.log(info.selectionText);
break;
}
});
Thanks once again for any help.
2
Answers
The main error has been that the script needs to be in the background, not run as a content script, as suggested by Barmar and erosman.
The secondary issue is that "onCreated" is not recognized when creating a context menu item. I replaced that with something from an example that Barmar provided, and I don't QUITE understand what the thing that replaces it does. It seems to be catching an error and sending it somewhere. The code is now working though, as seen below:
manifest.json
background.js
Content scripts WebExtension APIs are limited.
browser.contextMenus
is not available in the"content_scripts"
. It should be created and listened to in the background script.For example:
mainfest.json
Note:
alert()
is not available in the background script. Useconsole.log()
instead.