Custom context menu in Firefox with Add-on SDK?
firefox-addon-sdk, javascript
Solution
This code should only show the menu item when right-clicking on links directed at stackoverflow.com:
In your main module main.js:
exports.main = function() {
require("sdk/context-menu").Item({
label: "stack overflow link",
context: require("sdk/context-menu").SelectorContext("a[href]"),
contentScriptFile: require("sdk/self").data.url("check-node.js"),
onMessage: function(msg){},
});
};
In your content script (or content script file; in this case, check-node.js):
self.on("click",function(node,data){
self.postMessage("click");
});
self.on("context", function(node){
if(node.href && node.href.match(/^https?:\/\/(\w+\.)*stackoverflow\.com(\/.*)?$/))return true; //show in context menu if return value is true.
});
Re: Your sample code. You have `URLContext` which determines what pages your menu items show up on and this snippet `self.on("context", function(node) {return true; });` causes the menu item to always show when `URLContext` conditions are met. Use `SelectorContext` instead. And test the node.href as shown above, returning true only if you want the menu item to show.
Problem
I wish to add a single menu item to the firefox context menu that shows up only if the user right-clicks a specific url. I have a function to test the url. I used to do this by subscribing to "popupshowing" event and: ``` var item = document.getElementById("custom-menu-id"); if (item) // show only for specific links item.hidden = gContextMenu.onLink && acceptableURL(gContextMenu.linkURL); ``` I'm trying now to use the Add-on SDK, but there I no longer have access to gContextMenu. This snippet from the documentation doesn't work for me: ``` var cm = require("sdk/context-menu"); cm.Item({ label: "Copy name to clipboard", context: cm.URLContext("http://scholar.google*"), contentScript: 'self.on("context", function(node) {return true; });' }); ``` Here I'd think that it should be possible to get something like node.URL and test that, but it doesn't work. Maybe someone could suggest either how to get access to gContextMenu from the sdk or how to get URL from node or something else.