Issues with Content Menu and Opening Tabs - Chrome

2020-07-22 18:20发布

问题:

im having issue with the below code not showing up with selection is detected on the webpage.

Currently when i am selecting text the context menu is not showing up.

Code

 function getword(info,tab) {

 if (info.menuItemId == "google") {
console.log("Google" + info.selectionText + " was clicked.");
chrome.tabs.create({ 
    url: "http://www.google.com/search?q=" + info.selectionText,
})
 } else {
 console.log("Bing" + info.selectionText + " was clicked.");
  chrome.tabs.create({ 
    url: "http://www.bing.com/search?q=" +  info.selectionText,
 })
}
};

chrome.contextMenus.onClicked.addListener(getword);

chrome.runtime.onInstalled.addListener(function() {
  var contexts = ["page","selection","link","editable"];
  for (var i = 0; i < contexts.length; i++) {
    var context = contexts[i];
    var title = "Google Search";
    var id = chrome.contextMenus.create({"title": title, "contexts":[context],
                                     "id": "google"});
    console.log("'" + context + "' item:" + id);
   }
   chrome.contextMenus.create({"title": "Bing Search", "id": "child1"});

 });

回答1:

The value of the "id" property needs to be unique. You will see the following error if you view the console of your background page:

contextMenus.create: Cannot create item with duplicate id google
    at chrome-extension://ghbcieomgcdedebllbpimfgakljlleeb/background.js:23:34 

Do not call chrome.contextMenus.create for each context, but assign the list of contexts to the contexts key:

chrome.runtime.onInstalled.addListener(function() {
  var contexts = ["page","selection","link","editable"];
  var title = "Google Search";
  chrome.contextMenus.create({
    "title": title,
    "contexts": contexts,
    "id": "google"
  });
  // ...
});