我知道这个问题已经以不同的方式被反复询问过了,但我试图通过所有答案(希望我没有错过任何人),而且没有一个为我工作。Chrome扩展程序:从后台到内容脚本的sendMessage不起作用
这里是我的扩展代码:
清单:
{
"name": "test",
"version": "1.1",
"background":
{
"scripts": ["contextMenus.js"]
},
"permissions": ["tabs", "<all_urls>", "contextMenus"],
"content_scripts" : [
{
"matches" : [ "http://*/*" ],
"js": ["jquery-1.8.3.js", "jquery-ui.js"],
"css": [ "jquery-ui.css" ],
"js": ["openDialog.js"]
}
],
"manifest_version": 2
}
contextMenus.js
function onClickHandler(info, tab) {
if (info.menuItemId == "line1"){
alert("You have selected: " + info.selectionText);
chrome.extension.sendMessage({action:'open_dialog_box'}, function(){});
alert("Req sent?");
}
}
chrome.contextMenus.onClicked.addListener(onClickHandler);
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({"id": "line1", "type": "normal", "title": "I'm line 1", "contexts":["selection"]});
});
openDialog.js
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if (msg.action == 'open_dialog_box') {
alert("Message recieved!");
}
});
后台页面的两个警报工作,而其中一个content_script没有。
控制台日志消息:端口错误:无法建立连接。接收结束不存在。
我的错在哪里?
您应该使用'chrome.tabs.sendMessage()'将消息发送到内容脚本,而不是'chrome.extension.sendMessage()'。 – apsillers