use*_*880 14 javascript firefox firefox-addon firefox-addon-webextensions
我正在尝试将后台脚本中的变量发送到与HTML页面关联的内容脚本.内容脚本使用从后台脚本接收的变量更新HTML内容.
问题是我收到此错误消息:
Error: Could not establish connection. Receiving end does not exist.
Run Code Online (Sandbox Code Playgroud)
后台脚本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"]}
);
Run Code Online (Sandbox Code Playgroud)
该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>
Run Code Online (Sandbox Code Playgroud)
的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;
Run Code Online (Sandbox Code Playgroud)
的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"
]
}
Run Code Online (Sandbox Code Playgroud)
Mak*_*yen 10
你得到错误:
Error: Could not establish connection. Receiving end does not exist.
Run Code Online (Sandbox Code Playgroud)
当您试图通信(例如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".
它与URL 不匹配about:*.
有关Firefox在a webRequest.onErrorOccurred中获取事件时使用的URL的更多讨论main_frame,请参阅" 注入导航错误页面获取:错误:没有窗口匹配{"matchesHost":[""]} "