需要帮助为firefox附加组件创建多级上下文菜单

时间:2019-02-17 01:00:52

标签: javascript jquery html css firefox-addon

每当我单击US ID时,总会带我进入CA ID页面。

请帮助我更正后台代码。

谢谢。

manifest.json

{
    "manifest_version": 2,
    "name": "Amazon",
    "description": "Search on Amazon",
    "version": "1.0",
    "icons": {
        "48": "logo_48.jpg"
            },
    "permissions":["contextMenus"],
    "background": {
        "scripts": ["background.js"]
    }
}

background.js

browser.contextMenus.create({
    id: "US",
    title: "A US",
    contexts: ["selection"]
});


browser.contextMenus.create({
    id: "CA",
    title: "A CA",
    contexts: ["selection"]
});


//add action listener to the context menu
browser.contextMenus.onClicked.addListener(contextMenuAction);

function contextMenuAction(info, tab) {



    const url = "https://www.amazon.com/s?k=";

    browser.tabs.create({url: url});
        }


browser.contextMenus.onClicked.addListener(contextMenuAction);

function contextMenuAction(info, tab) {



    const url = "https://www.amazon.ca/s?k=";

    browser.tabs.create({url: url});
        }

1 个答案:

答案 0 :(得分:0)

您向可能单击的任何contextMenu项目添加了两个侦听器。因此,您有两个选择:

解决方案#1

将一项功能传递给每个项目的onclick选项

browser.contextMenus.create({
  id: "US",
  title: "A US",
  contexts: ["selection"],
  onclick: function () {
    browser.tabs.create({ url: "https://www.amazon.com/s?k=" })
  }
})

// do the same for the other contextMenu item created

解决方案2

添加一个侦听器,并使用menuItemId属性检查选择了哪个contextMenu项。

function contextMenuAction(info, tab) {
  if (info.menuItemId === "US") {
    browser.tabs.create({ url: "https://www.amazon.com/s?k=" })
  }

  if (info.menuItemId === "CA") {
    browser.tabs.create({ url: "https://www.amazon.ca/s?k=" })
  }