【问题标题】:Issues with Content Menu and Opening Tabs - Chrome Extension内容菜单和打开标签的问题 - Chrome 扩展
【发布时间】:2013-10-20 01:21:17
【问题描述】:

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

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

代码

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

 });

【问题讨论】:

    标签: javascript html json google-chrome-extension contextmenu


    【解决方案1】:

    "id" 属性的值必须是唯一的。查看the console of your background page会看到如下错误:

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

    【讨论】:

    • 完美运行,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2012-03-23
    • 1970-01-01
    相关资源
    最近更新 更多