Javascript 内容脚本可以连接到后台脚本,但popup.js无法连接到内容脚本

Javascript 内容脚本可以连接到后台脚本,但popup.js无法连接到内容脚本,javascript,google-chrome,google-chrome-extension,message-passing,Javascript,Google Chrome,Google Chrome Extension,Message Passing,在我的代码中,我当前有一个内容脚本,它向后台脚本发送消息,并作为响应创建一个警报。当访问https://www.google.com。但是,当尝试在popup.js和我的内容脚本之间建立通信时,我收到了错误消息 Could not establish connection. Receiving end does not exist. 我目前拥有的是,一旦单击弹出窗口上的按钮,我就会从popup.js发送一条消息。然后,应该显示内容脚本中的控制台消息,example.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"});
});

我尝试了很多答案,但到目前为止似乎没有一个有效。

弹出窗口脚本设计为不能直接与内容脚本对话,您必须通过后台脚本发送消息才能完成此任务


让弹出窗口先将消息发送到后台页面,让后台页面向特定内容脚本发送另一条消息。让您的内容脚本从后台页面收听事件。

谢谢您的回复,我尝试按照您所说的做,基本上是将同一个收听者添加到
background.js
(检查编辑是否清晰)但是我似乎也无法在后台脚本和
popup.js
之间建立连接。
弹出式脚本的设计目的是不能直接与内容脚本进行对话
-这不是真的。当弹出窗口显示时,弹出脚本可以直接与内容脚本通信。
甚至似乎没有到达
您所说的
似乎
是什么意思?在devtools中有一个调试器,可以准确地知道发生了什么。在内容脚本侦听器(devtools-Sources面板-content scrips)中设置一个断点,然后打开弹出窗口的devtools并单步执行代码或设置断点。这不会超过一分钟。@wOxxOm我也有同样的问题。将消息从弹出窗口发送到后台。尽可能设置断点。症状就像操作:
console.log(“浏览选项卡”+tabs[0].url)//这实际上发生了,但chrome.tabs.sendMessage没有发生。事实证明,问题是background.js返回了响应。所以,``chrome.runtime.onMessage.addListener(函数(response,sender,sendResponse){alert(response);sendResponse({msg:'allgood'})});所以alert(response)工作正常,但应该将msg:allgood从background.js发送到popup.js的sendResponse回调并没有完成它的工作。