I am trying to send a variable from a background script to a content script that is associated with an HTML page. The content script updates the HTML content with the variable received from the background script.
The problem is that I am getting this error message:
Error: Could not establish connection. Receiving end does not exist.
The background script 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"]}
);
The error.html
is:
<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>
The 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;
The 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"
]
}