2015-04-20 47 views
3

我正在建立一个带扩展菜单的扩展。见下面的代码。它应该如下工作:“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

不是签名chrome.contextMenus.onClicked.addListener(函数(资讯,标签){} ) –

+0

我试着添加“,标签”建议,但没有奏效。为了清楚起见,函数启动时,它们都会在任何menuItemId点击事件时启动,而不是仅在其menuItemId被点击时启动。 – JoeR

+0

我没有建议添加标签,我只是询问你使用'function addDoc(info)'或'function addLink(info)'而不是更直接的函数(info,tabs)。另外被点击的内容被传递给Info中的那个函数。 (所以info.id将是“添加链接”或“添加文档”,然后根据传入的值采取适当的操作。您是否只需要一个侦听器?https://developer.chrome.com/extensions/contextMenus –

回答

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"}); 
}); 
+0

我试过函数,结果是只有“else”部分工作,当任何一个菜单项被点击时,Wufoo都会启动,还有什么想法? – JoeR

+0

好吧,好消息,我现在强烈建议你调试应用程序,看看传递了什么值在通过信息,然后设置适当的条件,以在每种情况下获得所需的效果。一个简单的console.log(信息);在该函数的顶部将做伎俩....... –

+0

感谢您的帮助我改变了“info.i d“到”info.menuItemId“并且它可以工作。 – JoeR