当用户在上下文菜单中单击我的项目时,我想从background.js
发送一条消息,并在我的内容脚本script.js
中侦听它,以便我可以运行一些代码操纵DOM。无法获取chrome.runtime.onMessage来侦听
我原样复制了Chrome Message Parsing docs的示例代码,但是我无法获取侦听器函数来触发。
这是我的manifest.json
文件:
{
"manifest_version": 2,
"name": "Background image downloader",
"description": "Easily lets you download images that are set as background-image in CSS",
"version": "0.0.1",
"permissions": [
"tabs",
"contextMenus"
],
"web_accessible_resources": [
"script.js"
],
"icons": {
"16": "assets/icon_16.png",
"48": "assets/icon_48.png",
"128": "assets/icon_128.png"
},
"background" : { "scripts": ["background.js"] }
}
这里的background.js
:
// Inject the content script into each page (script.js)
// http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script
var s = document.createElement("script");
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
this.parentNode.removeChild(this);
};
(document.head || document.documentElement).appendChild(s);
// Handle the click on the context menu
function getClickHandler(info, tab) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
console.log(tabs[0].id);
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
};
// Create the context menu
chrome.contextMenus.create({
"title" : "Download image",
"type" : "normal",
"contexts" : ["all"],
"onclick" : getClickHandler
});
而这里的script.js
:
console.log('script.js loaded');
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
debugger // This never gets triggered
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello")
sendResponse({farewell: "goodbye"});
});
我在做什么错?
请参阅[扩展架构](https://developer.chrome.com/extensions/overview#arch)。您正在将脚本元素注入到背景页面中。它不是[内容脚本](https://developer.chrome.com/extensions/content_scripts)。查看[官方示例扩展](https://developer.chrome.com/extensions/samples)获取实际工作代码(特别是通过'executeScript'过滤列表) – wOxxOm