我知道这个问题已经以不同的方式被反复提出,但我尝试过一遍所有的答案(希望我没有错过任何人),但没有一个对我有用。
这是我的扩展程序的代码:
list :
{
"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.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {action: "open_dialog_box"}, function(response) {});
});
而不是像您目前那样使用chrome.extension.sendMessage
。
chrome.tabs
变体将消息发送到内容脚本,而 chrome.extension
函数将消息发送到所有其他扩展组件。
关于background - 从扩展后台或弹出窗口发送消息到内容脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14245334/