简体   繁体   English

Firefox中带有附加SDK的自定义上下文菜单?

[英]Custom context menu in Firefox with Add-on SDK?

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. 我希望在firefox上下文菜单中添加一个菜单项,仅当用户右键单击特定URL时才会显示该菜单项。 I have a function to test the url. 我有一个测试网址的功能。 I used to do this by subscribing to "popupshowing" event and: 我曾经通过订阅“popupshowing”事件来做到这一点,并且:

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. 我现在正在尝试使用Add-on SDK,但我无法再访问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. 在这里,我认为应该可以获得像node.URL这样的东西并测试它,但它不起作用。 Maybe someone could suggest either how to get access to gContextMenu from the sdk or how to get URL from node or something else. 也许有人可以建议如何从sdk访问gContextMenu或如何从节点或其他东西获取URL。

This code should only show the menu item when right-clicking on links directed at stackoverflow.com : 此代码应仅在右键单击指向stackoverflow.com的链接时显示菜单项:

In your main module main.js : 在主模块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 ): 在您的内容脚本(或内容脚本文件;在本例中为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. Re:您的示例代码。 You have URLContext which determines what pages your menu items show up on and this snippet self.on("context", function(node) {return true; }); 你有URLContext来确定你的菜单项显示的页面和这个片段self.on("context", function(node) {return true; }); causes the menu item to always show when URLContext conditions are met. 导致菜单项始终显示满足URLContext条件。 Use SelectorContext instead. 请改用SelectorContext And test the node.href as shown above, returning true only if you want the menu item to show. 并测试node.href,如上所示,仅当您希望显示菜单项时才返回true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM