Firefox webextension 错误:无法建立连接。接收端不存在

新手上路,请多包涵

我正在尝试将变量从后台脚本发送到与 HTML 页面关联的内容脚本。内容脚本使用从后台脚本接收到的变量更新 HTML 内容。

问题是我收到此错误消息:

 Error: Could not establish connection. Receiving end does not exist.

后台脚本 main.js

 var target = "<all_urls>";
function logError(responseDetails) {
  errorTab = responseDetails.tabId;
  console.log("Error tab: "+errorTab);

  errorURL = responseDetails.url;
  console.log("Error URL: "+errorURL);

  //send errorURL variable to content script
  var sending = browser.tabs.sendMessage(errorTab, {url: errorURL})
    .then(response => {
      console.log("Message from the content script:");
      console.log(response.response);
    }).catch(onError);

  //direct to HTML page
  browser.tabs.update(errorTab,{url: "data/error.html"});
}//end function

browser.webRequest.onErrorOccurred.addListener(
  logError,
  {urls: [target],
  types: ["main_frame"]}
);

error.html 是:

 <html>
<head>
  <meta charset="UTF-8">
</head>
<body>
  The error received is <span id="error-id"></span>
  <script src="content-script.js"></script>
</body>
</html>

content-script.js

 //listen to errorURL from the background script.
browser.runtime.onMessage.addListener(request => {
  console.log("Message from the background script:");
  console.log(request.url);
  return Promise.resolve({response: "url received"});
}); //end onMessage.addListener

//update the HTML <span> tag with the error
document.getElementById("error-id").innerHTML = request.url;

manifest.json

 {
  "manifest_version": 2,
  "name": "test",
  "version": "1.0",
  "background": {
    "scripts": ["main.js"]
  },

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["webextension/data/content-script.js"]
    }
  ],

  "permissions": [
    "<all_urls>",
    "activeTab",
    "tabs",
    "storage",
    "webRequest"
  ]
}

原文由 user6875880 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答

你得到错误:

 Error: Could not establish connection. Receiving end does not exist.

当您尝试与内容脚本未侦听消息的选项卡通信(例如 tabs.sendMessage() , tabs.connect() )时。这包括选项卡中不存在内容脚本的时间。

您不能将内容脚本注入 about:* URL

对于您的问题,您收到此错误是因为没有在选项卡中注入内容脚本。当您尝试发送消息时,在 main_frame webRequest.onErrorOccurred 事件中,选项卡的 URL 已经是 about:neterror?[much more, including the URL where the error occurred]不能将内容脚本注入 about:* URL 。因此,收听消息的选项卡中没有内容脚本。

具体来说,您在 manifest.json 中使用了 <all_urls> 匹配模式 content_scripts 条目。 <all_urls> 匹配:

特殊值 "<all_urls>" 匹配任何受支持方案下的所有 URL:即“http”、“https”、“file”、“ftp”、“app”。

匹配 about:* URL。

有关 Firefox 在 webRequest.onErrorOccurred 中获取 main_frame 事件时使用的 URL 的更多讨论,请参阅“ 注入导航错误页面获取:错误:没有窗口匹配 {“matchesHost”: [“”]}

原文由 Makyen 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于扩展开发人员:如果您重新加载您的扩展(作为开发循环的正常部分), _它会切断与内容脚本的所有连接_。

您必须记住还需要重新加载页面,以便内容脚本重新正确收听。

原文由 Offirmo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题