【发布时间】:2017-04-01 21:20:59
【问题描述】:
在我的代码中,我目前有一个向后台脚本发送消息的内容脚本,并作为响应创建一个警报。这适用于example.js 和background.js 访问https://www.google.com 时。但是,当尝试在 popup.js 和我的内容脚本之间建立通信时,我收到了错误消息
Could not establish connection. Receiving end does not exist.
我目前拥有的是,一旦单击弹出窗口上的按钮,我就会从 popup.js 发送一条消息。然后,应该从内容脚本example.js 中显示一条控制台消息,但它甚至似乎都没有到达内容脚本的侦听器。这是代码,
popup.js:
window.onload=function(){
document.getElementById('highlight').addEventListener('click', sendHighlightMessage, false);
}
function sendHighlightMessage() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
console.log("going through tabs " + tabs[0].url); //this actually occurs
chrome.tabs.sendMessage(tabs[0].id, {highlight: true}, function(response) {
if (chrome.runtime.lastError) {
// An error occurred :(
console.log("ERROR: ", chrome.runtime.lastError);
}
else{
console.log(response.message);
}
});
});
}
example.js:
chrome.runtime.sendMessage('Hello World');
chrome.tabs.onMessage.addListener(function(response, sender, sendResponse){
console.log("received " + response); //never gets to this point
sendResponse({message : "Response Received"});
});
background.js:
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
alert(response);
});
chrome.tabs.onMessage.addListener(function(response, sender, sendResponse){
console.log("received " + response);
sendResponse({message : "Response Received"});
});
我已经尝试了很多答案,但到目前为止似乎都没有奏效。
【问题讨论】:
-
doesn't even seem to be reachingseem是什么意思?您在 devtools 中有一个调试器,可以确切地知道发生了什么。在内容脚本侦听器中设置断点(devtools - 源面板 - 内容脚本),然后打开弹出窗口的 devtools 并单步执行代码或设置断点。这应该不会超过一分钟。 -
@wOxxOm 我也有同样的问题。将消息从弹出窗口发送到后台。尽可能设置断点。类似 OP 的症状:
console.log("going through tabs " + tabs[0].url); //this actually occurs andchrome.tabs.sendMessage 不会发生 -
编辑:原来问题是从 background.js 得到响应。所以,``` chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){ alert(response); sendResponse({msg:'allgood'}) });所以 alert(response) 工作正常,但是应该将 msg:allgood 从 background.js 发送到 popup.js 的 sendResponse 回调没有完成它的工作。
标签: javascript google-chrome google-chrome-extension message-passing