我知道這個問題已經以不同的方式被反覆詢問過了,但我試圖通過所有答案(希望我沒有錯過任何人),而且沒有一個爲我工作。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