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

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

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

我在尝试从弹出窗口向我的contentscript发送消息时遇到此错误。我想做的是从我的content.js中获取当前选项卡的文档,并将其发送到弹出窗口。我该如何修复这个错误?

{
  "manifest_version": 2,
  "name": "Chrome Snapshot",
  "description": "Save images and screenshots of sites to Dropbox.",
  "version": "1.0",
  "permissions": [
    "<all_urls>",
    "tabs"
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "html/popup.html"
  },
  "background": {
    "scripts": [
      "vendor/dropbox.min.js",
      "vendor/jquery-2.0.2.min.js"
    ],
    "persistant": false
  },
  "content_scripts" : [{
    "all_frames": true,
    "matches" : ["*://*/*"],
    "js" : ["js/content.js"],
    "run_at": "document_end"
  }]
}

js/popup.js

chrome.runtime.sendMessage({message: 'hi'}, function(response) {
  console.log(response);
});

js/content.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  console.log('message', message);
  sendResponse({farewell: 'goodbye'}); 
});

编辑#1仍然得到相同的错误Port error: Could not establish connection. Receiving end does not exist. miscellaneous_bindings:235 chromeHidden.Port.dispatchOnDisconnect

修复了清单中拼写错误的"persistent"
更新js/popup.js

chrome.tabs.query({'active': true,'currentWindow':true}, function(tab){
    console.log('from tab', tab[0]);
    chrome.tabs.sendMessage(tab[0].id, {message: 'hi'}, function(response){
      console.log(JSON.stringify(response));
    });
  });

您需要使用chrome.tabs.sendMessage向内容脚本发送消息。来自chrome开发者网站上的chrome.runtime.sendMessage规范:

请注意,扩展无法使用此方法向内容脚本发送消息。要将消息发送到内容脚本,请使用tabs.sendMessage.

如果这对你来说不是一个好的选择,你可以让每个内容脚本打开一个到后台页面的端口(这可能需要持久化),然后让弹出页面向后台页面发送一条消息,后台页面会通过每个端口将消息中继到所有内容脚本,告诉他们将消息发送回弹出页面。(使用chrome.runtime.connect。)

此外,您在清单文件中拼错了"persistent"。我不希望你必须在代码中挖掘半个小时后才发现这导致了问题。