3

我在网页上检测到以下代码未显示选择时遇到问题。

目前,当我选择文本时,上下文菜单未显示。

代码

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

 });
4

1 回答 1

6

财产的价值"id"必须是唯一的。如果您查看后台页面的控制台,您将看到以下错误:

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

不要chrome.contextMenus.create为每个上下文调用,而是将上下文列表分配给contexts键:

chrome.runtime.onInstalled.addListener(function() {
  var contexts = ["page","selection","link","editable"];
  var title = "Google Search";
  chrome.contextMenus.create({
    "title": title,
    "contexts": contexts,
    "id": "google"
  });
  // ...
});
于 2013-10-11T20:58:36.213 回答