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

Javascript Chrome扩展:端口错误:无法建立连接。接收端不存在。,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,尝试在我的内容脚本和背景脚本之间进行通信时,我遇到以下错误: 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

尝试在我的内容脚本和背景脚本之间进行通信时,我遇到以下错误:

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);
function contactBackground(nachricht){
    chrome.extension.sendMessage({message: nachricht}, function(response) {
        console.log("The Background Script got the following Message: " + response.message);
    });
}
streamcloud.js

function onRequest(request, sender, callbackFunction) {
    console.log("Me (BS) became this Message:" + request.message);
    sendResponse({message: request.message})
};
chrome.extension.onRequest.addListener(onRequest);
function contactBackground(nachricht){
    chrome.extension.sendMessage({message: nachricht}, function(response) {
        console.log("The Background Script got the following Message: " + response.message);
    });
}
以及我的manifest.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.html”和一个空的background.html,但由于自清单版本2以来不支持背景页面,我不能使用它。

而不是

chrome.extension.onRequest.addListener(onRequest);
使用

因为您使用的是sendMessage而不是sendRequest

消息解析已在新版Chrome中更新。sendRequest和onRequest已被弃用。建议使用sendMessage和onMessage


请参阅文档以了解。

sendMessage
onRequest
不兼容

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

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

对于Chrome 20-25,使用
Chrome.extension.onMessage
Chrome.extension.sendMessage


对于Chrome 26+,请使用和


注意:从Chrome 26开始,不推荐的方法仍然受支持,尽管没有文档记录。如果有机会,请更新扩展以使用新方法,以确保扩展将来仍能工作。

有关创建与Chrome 20+兼容的浏览器的代码,请参阅。

另一种方法,它解决了我的问题,但存在完全相同的错误:这适用于Chrome 20-25。在Chrome 26中,API再次发生了变化。也看到了。