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

时间:2013-04-06 13:58:28

标签: javascript firefox-addon-sdk

我希望将单个菜单项添加到显示的firefox上下文菜单中 仅当用户右键单击特定URL时。我有一个测试网址的功能。 我以前通过订阅" popupshowing"来做到这一点。事件和:

var item = document.getElementById("custom-menu-id");
if (item) // show only for specific links
    item.hidden = gContextMenu.onLink && acceptableURL(gContextMenu.linkURL);

我现在正在尝试使用附加SDK,但我无法再访问gContextMenu。 文档中的这段代码对我不起作用:

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; });'
});

在这里,我认为应该可以获得像node.URL这样的东西并测试一下, 但它不起作用。也许有人可以建议如何从sdk访问gContextMenu或如何从节点或其他东西获取URL。

1 个答案:

答案 0 :(得分:4)

此代码只应在右键单击指向 stackoverflow.com 的链接时显示菜单项:

在主模块中 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){},
    });
};

在您的内容脚本(或内容脚本文件;在本例中为 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:您的示例代码。您有URLContext来确定您的菜单项显示在哪些页面上,此代码段self.on("context", function(node) {return true; });会导致菜单项始终在符合URLContext条件时显示。请改用SelectorContext。并测试node.href,如上所示,仅当您希望显示菜单项时才返回true。

相关问题