47

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

控制檯日誌消息:端口錯誤:無法建立連接。接收結束不存在。

我的錯在哪裏?

+0

您應該使用'chrome.tabs.sendMessage()'將消息發送到內容腳本,而不是'chrome.extension.sendMessage()'。 – apsillers

回答

89

在你的後臺頁面,你應該叫

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函數將消息發送到所有其他擴展組件。

+4

謝謝你。除了'chrome.tabs.sendMessage' [必須指定哪個標籤發送給它](http://developer.chrome.com/extensions/messaging.html)之外,這是正確的。因此,解決方案更改爲:chrome.tabs.query({active:true},function(tabs){} {} {} {}} chrome.tabs.sendMessage(tab.id,{action:「open_dialog_box」},function(response) { \t \t \t}); \t \t});' – Subway

+1

哎呀,當然是。我會更新我的答案。 – apsillers

+0

好的,我刪除了我添加到問題中的編輯。 – Subway

相關問題