【chrome扩展】Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
未被选中的runtime.lastError。无法建立连接。接收端不存在。
向background.js发送通信消息,发送失败,一直报这个错误
配置项加一个配置就可以
"manifest_version": 3,
...
"externally_connectable": {
"matches": ["*://*.example.com/*"]
},
通信代码示例,仅供参考。
// background.js
chrome.runtime.onMessageExternal.addListener(
function (request, sender, sendResponse) {
console.log("收到请求消息:", request)
sendResponse({ goodbye: "goodbye" });
}
);
成功输出:
收到请求消息: {message: '你好~'}
// content.js
chrome.runtime.sendMessage(extensionId, { "message": "你好~" }, (response) => {
// 3. Got an asynchronous response with the data from the background
console.log('收到处理结果:', response);
});
成功输出:
收到处理结果: {goodbye: 'goodbye'}
manifest.json格式参考(V3):
https://developer.chrome.com/docs/extensions/mv3/manifest/
完整案例参考:
https://github.com/ttglad/chrome-extension-v3-demo