端口错误:无法建立连接.接收端不存在

Port error: Could not establish connection. Receiving end does not exist

本文关键字:建立 连接 接收端 不存在 错误      更新时间:2023-09-26

我一直在谷歌周围广泛试图补救这个问题,但似乎不能找到一个解决方案。我想做一个简单的任务,在我的Chrome扩展设置一个监听器和发送器。

我的清单

{
  "manifest_version": 2,
  "name": "my app",
  "description": "text",
  "version": "0.1",
  "background":{
    "scripts":["background.js"]
  },
  "content_scripts": [
    {
      // http://developer.chrome.com/extensions/match_patterns.html
      "matches": ["http://myurl.com/*"],
      "js": ["jquery-1.9.1.min.js", "myapp.js"],
      "all_frames": true
    }
  ], 
  "browser_action": {
    "default_icon": "/icons/icon-mini.png",
    "default_popup": "popup.html"
  }
}

In my background JS

chrome.tabs.getSelected(null, function(tab) {
  chrome.tabs.sendMessage(tab.id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});

在我的pop - up.js中(由coffeescript呈现,请原谅这种奇怪的语法)

(function() {
  $(function() {});
  chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    if (console.log(sender.tab)) {
      "from a content script:" + sender.tab.url;
    } else {
      "from the extension";
    }
    if (request.greeting === "hello") {
      return sendResponse({
        farewell: "goodbye"
      });
    }
  });
}).call(this);

在myapp.js中

chrome.extension.sendMessage({
      greeting: "hello"
    }, function(response) {
      return console.log(response.farewell);
    });

我遵循了教程。不知道为什么这不起作用。我很体面的JS,非常不清楚为什么这是奇怪的行为。任何帮助将非常感激!

这段代码有不止一个问题,所以让我把它分解一下。

从我看到你正试图从你的内容脚本发送到弹出窗口的消息,有一个背景页不做任何事情。

问题1

在popup.js的代码,除了奇怪的复杂,不是一个背景页面。它只在popup打开时运行,因此它将无法侦听消息。

问题# 2

后台页面中的代码是使用贬值的getSelected方法向内容脚本发送消息。内容脚本没有监听器。

这两件事的结果是:

Background page -> content script (no listener)
Content Script -> extension pages (no listener)

我建议把你的背景页面作为你交流的中心。如果你需要在你的弹出和内容脚本之间进行通信,使其popup -> content script和使用sendResponse()来回复。

编辑:这是一个你想要的消息传递的例子。用你的变量替换。

内容脚本

...
//get all of your info ready here
chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
  //this will fire when asked for info by the popup
  sendResponse(arrayWithAllTheInfoInIt);
});

弹出

...
chrome.tabs.query({'active': true,'currentWindow':true},function(tab){
  //Be aware 'tab' is an array of tabs even though it only has 1 tab in it
  chrome.tabs.sendMessage(tab[0].id,"stuff", function(response){
    //response will be the arrayWithAllTheInfoInIt that we sent back
    //you can do whatever you want with it here
    //I will just output it in console
    console.log(JSON.stringify(response));
  });
});

我在后台页面遇到了类似的问题,我的解决方案是确保选项卡在尝试发送消息之前完成加载。

如果选项卡没有完全加载,内容脚本将没有启动,也不会等待消息。

下面是一些代码:

 chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
   if (changeInfo.status === 'complete') {
     // can send message to this tab now as it has finished loading
   }
 }

所以如果你想发送消息到活动选项卡,你可以确保它已经完成加载。