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

相关问题