如何在ContextMenu上运行脚本单击Chrome扩展

时间:2017-03-04 00:36:51

标签: javascript google-chrome google-chrome-extension google-chrome-devtools

我试图在ContextMenu Click事件上运行脚本。我使用了example ContextMenu,它们有清单:

{
"name": "Context Menus Sample (with Event Page)",
"description": "Shows some of the features of the Context Menus API using an event page",
"version": "0.7",
"permissions": ["contextMenus"],
"background": {
"persistent": false,
"scripts": ["sample.js"]
},
"manifest_version": 2
}

sample.js:

function onClickHandler(info, tab) {
chrome.tabs.executeScript(null,
  {code:"document.body.style.backgroundColor='" + e.target.id + "'"});
};
chrome.contextMenus.onClicked.addListener(onClickHandler);
chrome.runtime.onInstalled.addListener(function() {
var contexts = ["page","selection","link","editable","image","video",
              "audio"];
for (var i = 0; i < contexts.length; i++) {
var context = contexts[i];
var title = "Test '" + context + "' menu item";
var id = chrome.contextMenus.create({"title": title, "contexts":[context],
                                     "id": "context" + context});
}

chrome.contextMenus.create({"title": "Oops", "id": "child1"}, function() {
if (chrome.extension.lastError) {
  console.log("Got expected error: " + chrome.extension.lastError.message);
  }
   });
});

我还将onclick处理程序更改为:

function onClickHandler(info, tab) {
chrome.tabs.executeScript(null, {file: "content.js"});
};

当content.js为:

document.body.innerHTML = document.body.innerHTML.replace(new RegExp("text", "gi"), "replaced");

但两者都不起作用。怎么解决?

0 个答案:

没有答案