I'm trying to capture security information about outbound connections in a WebExtension (I happen to be targeting Firefox first).
This information will be processed within a background script process running on the browser, and ultimately used for updating the visual appearance of a browser action to give easier access to some additional information about the connection's certifying authority.
However, when my code calls sendMessage
, it yields the error
Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
—despite the fact that the onMessage
listener had already been added!
Instead of yielding this error, sendMessage
should trigger the callback previously registered via onMessage.addListener
. What do I have to do to achieve this result?
The code can be found in the following two code blocks, and is easily tested by saving them into a folder, going to about:debugging
>“This Firefox”>“Load Temporary Add-on…”>manifest.json
>“test1: Inspect”, then loading any HTTPS website in another tab.
//background.js
//Create onMessage callback
function f(message,sender,callback) {
console.log("onMessage listener caught a message!");
console.log("here it is:", message);
}
//Enable onMessage callback
console.log("Adding onMessage listener...");
browser.runtime.onMessage.addListener(f);
//(verify it was enabled)
if(browser.runtime.onMessage.hasListener(f)){
console.log("onMessage listener added successfully!");
} else {
console.error("FAILED TO ADD onMessage LISTENER!",f);
}
//Create onHeadersReceived callback
async function g(details){
let message={
details: details,
securityInfo: await browser.webRequest.getSecurityInfo(details.requestId, {certificateChain:true})
};
console.log('onSendHeaders event triggered\n\nMore information:',message);
console.log('Sending via sendMessage\u2026');
browser.runtime.sendMessage(message);
}
//Enable onHeadersReceived callback
console.log("Adding onHeadersReceived listener...");
browser.webRequest.onHeadersReceived.addListener(g,
{
types:['main_frame'],
urls:['<all_urls>']
},
['blocking']
);
//(verify it was enabled)
if(browser.webRequest.onHeadersReceived.hasListener(g)){
console.log("onHeadersReceived listener added successfully!")
} else {
console.error("FAILED TO ADD onHeadersReceived LISTENER!",g);
}
//manifest.json
{
"manifest_version": 2,
"name": "test1",
"version": "0.0.1",
"description": "AAAAaaaaAAaA",
"permissions": [
"webRequest","webRequestBlocking",
"<all_urls>"
],
"background": {
"scripts": ["background.js"]
}
}