【问题标题】:Content script can connect to background script but popup.js cannot connect to content script内容脚本可以连接到后台脚本,但 popup.js 无法连接到内容脚本
【发布时间】:2017-04-01 21:20:59
【问题描述】:

在我的代码中,我目前有一个向后台脚本发送消息的内容脚本,并作为响应创建一个警报。这适用于example.jsbackground.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 reaching seem 是什么意思?您在 devtools 中有一个调试器,可以确切地知道发生了什么。在内容脚本侦听器中设置断点(devtools - 源面板 - 内容脚本),然后打开弹出窗口的 devtools 并单步执行代码或设置断点。这应该不会超过一分钟。
  • @wOxxOm 我也有同样的问题。将消息从弹出窗口发送到后台。尽可能设置断点。类似 OP 的症状:console.log("going through tabs " + tabs[0].url); //this actually occurs and chrome.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


【解决方案1】:

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

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

【讨论】:

  • 感谢您的回复,我尝试按照您所说的基本上向background.js 添加相同的侦听器(检查编辑是否清晰),但我似乎无法在背景之间建立联系脚本和popup.js
  • Popups scripts were designed not to be able to talk to content scripts directly - 这不是真的。弹出脚本可以直接与内容脚本进行通信当弹出窗口显示时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 2014-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多