我正在使用上下文菜单构建chrome扩展。见下面的代码。它应该如下工作:“Connect-It”上下文项是父项,并在单击/悬停时显示子菜单中的两个子项(添加链接,添加文档)。单击特定子项时,新选项卡将打开一个新URL。相反,如果单击任一子项,则两个新URl都将打开。她是我的代码。我该如何解决这个问题?
// background.js
// Parent Level context menu item
chrome.runtime.onInstalled.addListener(function() {
var id = chrome.contextMenus.create({
id: "Connect-IT", // Required for event pages
title: "Connect-IT",
contexts: ["all"],
});
});
// child level contextmenu items
chrome.runtime.onInstalled.addListener(function() {
var id = chrome.contextMenus.create({
id: "Add a Link",
parentId: "Connect-IT",
title: "Add a Link",
contexts: ["all"],
});
});
chrome.runtime.onInstalled.addListener(function() {
var id = chrome.contextMenus.create({
id: "Add a Doc",
parentId: "Connect-IT",
title: "Add a Doc",
contexts: ["all"],
});
});
// click handler below. This is what's broken. If either Child Menu Item is clicked both of the function below execute
// launching the two web pages. If one menu item is clicked only the website with taht item shoudl launch.
chrome.contextMenus.onClicked.addListener(function addLink(info){ menuItemId="Add a Link",
chrome.tabs.create({url: "https://www.wufoo.com"});
})
chrome.contextMenus.onClicked.addListener(function addDoc(info){ menuItemId="Add a Doc",
chrome.tabs.create( {url: "https://www.google.com"});
})
答案 0 :(得分:2)
只需替换这两个陈述
chrome.contextMenus.onClicked.addListener(function addLink(info){ menuItemId="Add a Link",
chrome.tabs.create({url: "https://www.wufoo.com"});
})
chrome.contextMenus.onClicked.addListener(function addDoc(info){ menuItemId="Add a Doc",
chrome.tabs.create( {url: "https://www.google.com"});
})
使用这个单一陈述
chrome.contextMenus.onClicked.addListener(function(info, tabs){
if ( info.menuItemId === 'Add a Link' )
chrome.tabs.create( {url: "https://www.google.com"});
else
chrome.tabs.create({url: "https://www.wufoo.com"});
});