Chrome扩展程序:将功能附加到右键菜单

Ski*_*zit 30 javascript google-chrome-extension

如何将功能添加到浏览器中的右键菜单?例如,something附加到右键菜单,该菜单dosomething()具有位于我的扩展中的功能.

Anu*_*rma 27

我使用contextMenu API - 链接进行了简单的扩展
希望这很好用作例子.

manifest.json -

{
  "manifest_version": 2,
  ...
  ...
  "permissions": [
      "contextMenus", 
      "tabs"],
  ...
  ...
  "background": {"page": "background.html"}
}
Run Code Online (Sandbox Code Playgroud)

main.js -

 searchUrbanDict = function(word){
    var query = word.selectionText;
    chrome.tabs.create({url: "http://www.urbandictionary.com/define.php?term=" + query});
 };

chrome.contextMenus.create({
 title: "Search in UrbanDictionary",
 contexts:["selection"],  // ContextType
 onclick: searchUrbanDict // A callback function
});
Run Code Online (Sandbox Code Playgroud)

有关不同上下文类型的更多信息 - 链接


Jef*_*zik 9

Anurag-Sharma 的答案针对清单 v3 进行了更新:

清单.json -

{
    "name": "terapeak",
    "description": "easy way to research ebay products",
    "version": "1.0",
    "manifest_version": 3,
    "permissions": [
        "contextMenus",
        "tabs"
    ],
    "background": {
        "service_worker": "main.js"
    }
}
Run Code Online (Sandbox Code Playgroud)

main.js

searchTerapeak = function(word){
    var query = word.selectionText;
    chrome.tabs.create({url: "https://www.ebay.com/sh/research?dayRange=365&sorting=-avgsalesprice&tabName=SOLD&keywords="
+ query});  };

chrome.contextMenus.removeAll(function() {
    chrome.contextMenus.create({
     id: "1",
     title: "Terapeak this!",
     contexts:["selection"],  // ContextType
    }); })

chrome.contextMenus.onClicked.addListener(searchTerapeak);
Run Code Online (Sandbox Code Playgroud)

为什么每次都需要removeAll:为什么chrome.contextMenus会创建多个条目?