Chrome context menu functions launching everything at once
I am creating a chrome extension with context menus. See code below. It should work like this: the "Connect-It" contextual element is the parent element and shows two children (add link, add document) in a submenu on click / hover. When clicking on a specific child element, a new tab opens a new URL. Instead, if any child is clicked, a new URl will open. This is my code. How to fix it?
// 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 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"});
})
+3
source to share
1 answer
just replace these two statements
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"});
})
with this single statement
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"});
});
+2
source to share