本文介绍了Chrome 扩展:端口错误:无法建立连接.接收端不存在.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在我的内容脚本和后台脚本之间进行通信时,出现以下错误:

When trying to communicate between my Content- and Background Script I get the following errors:

Port error: Could not establish connection. Receiving end does not exist.
Error in event handler for 'undefined': Cannot read property 'message' of undefined       
TypeError: Cannot read property 'message' of undefined

background.js

function onRequest(request, sender, callbackFunction) {
    console.log("Me (BS) became this Message:" + request.message);
    sendResponse({message: request.message})
};
chrome.extension.onRequest.addListener(onRequest);

streamcloud.js

function contactBackground(nachricht){
    chrome.extension.sendMessage({message: nachricht}, function(response) {
        console.log("The Background Script got the following Message: " + response.message);
    });
}

和我的ma​​nifest.json

{
  "name": "InstantWatch - Dev",
  "manifest_version": 2,
  "version": "0.7",
  "permissions": ["tabs", "http://*/", "https://*/"],
  "background": {
    "scripts": ["background.js"]
  },  
  "browser_action": {
    "default_title": "InstantWatch",
    "default_icon" : "icon.ico"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "http://*/*"],
      "js": ["jquery.js", "streamcloud.js"]
    }
  ]
}

我找到了添加 background_page: "background.html" 和一个空的 background.html 的解决方案,但是因为由于 manifest_version: 2 不支持 background_page,所以我不能使用它.

I found the solution to add an background_page: "background.html" with an empty background.html, but since background_page isn't supported since manifest_version: 2, I can't use that.

推荐答案

sendMessageonRequest 不兼容.

如果您需要支持 Chrome 19 及更早版本,请使用 onRequestsendRequest:

If you need to support Chrome 19 and earlier, use onRequest and sendRequest:

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    // Warning: Chrome 19- [receiver]
});
chrome.extension.sendRequest(message, optional_sendResponse);

对于 Chrome 20 - 25,使用 chrome.extension.onMessagechrome.extension.sendMessage:


For Chrome 20 - 25, use chrome.extension.onMessage and chrome.extension.sendMessage:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    // Chrome 20+
});
chrome.extension.sendMessage(message, optional_sendResponse);

对于 Chrome 26+,使用 chrome.runtime.onMessagechrome.runtime.sendMessage.


For Chrome 26+, use chrome.runtime.onMessage and chrome.runtime.sendMessage.

注意:从 Chrome 26 开始,仍然支持已弃用的方法,尽管没有记录.如果有机会,请更新您的扩展程序以使用新方法,以确保您的扩展程序将来仍能正常工作.
有关创建与铬 20+.

Note: As of Chrome 26, the deprecated methods are still supported, albeit undocumented. If you get a chance, update your extension to use the new methods, to ensure that your extension will still work in the future.
See this answer for code to create a which is compatible with Chrome 20+.

这篇关于Chrome 扩展:端口错误:无法建立连接.接收端不存在.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 18:33