我正在尝试将变量从后台脚本发送到与 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 许可协议
你得到错误:
当您尝试与内容脚本未侦听消息的选项卡通信(例如
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>
匹配:它 不 匹配
about:*
URL。有关 Firefox 在
webRequest.onErrorOccurred
中获取main_frame
事件时使用的 URL 的更多讨论,请参阅“ 注入导航错误页面获取:错误:没有窗口匹配 {“matchesHost”: [“”]} ”