Chrome右键菜单子项功能同时启动的问题

3

我正在构建一个包含上下文菜单的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"});
})

不是这个签名 chrome.contextMenus.onClicked.addListener(function(info, tabs){}) 吗? - Code Uniquely
我尝试按建议添加“,tabs”,但没有起作用。明确一下,这些函数是启动的,只是在任何menuItemId点击事件上都会同时启动,而不仅仅是在它们的menuItemId被点击时启动。 - JoeR
我并没有建议添加选项卡,我只是质疑你使用 'function addDoc(info)' 或 'function addLink(info)' 而不是更简单直接的 'function(info, tabs)'。同时,被点击的内容通过 Info 传递到了那个函数中(所以 info.id 将是 "Add a Link" 或者 "Add a Doc",然后你可以根据传入的值采取适当的行动)。难道你只需要一个监听器。https://developer.chrome.com/extensions/contextMenus - Code Uniquely
我猜这就是我困惑的地方。我只是一个初级程序员。似乎无法弄清楚代码如何使一个addListener仅调用被点击项目中适当的函数。 - JoeR
1个回答

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

我尝试了那个函数,结果只有“否则”部分起作用。当单击任一菜单项时,Wufoo就会启动。还有其他想法吗? - JoeR
好的,很好的消息,我现在强烈建议您调试应用程序,并查看通过信息传递的值,然后设置适当的if条件以在每种情况下获得所需的效果。函数顶部的简单console.log(info)将解决问题...... - Code Uniquely
谢谢帮助。我把“info.id”改成了“info.menuItemId”,现在可以正常工作了。 - JoeR
所以,我已经更新了答案以显示 - 你能接受答案为正确吗? - Code Uniquely

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接