I’ve written an extension with a non-persistent background script (using manifest v3 without specifying persistent=false explicitly as this should be the default for v3). There is a content script that tries to send a message to the background script when the user clicks on a link by calling browser.runtime.sendMessage(...)
. The background script installs an event handler like this:
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
// ...
})
After a while, when clicking on a link for the first time, sending the message to the background script fails with “Error: Could not establish connection. Receiving end does not exist.”. It works when clicking a second time. As I understand it, this should work even when the background script has been unloaded, at least according to https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Background_scripts#add_listeners :
Defining relevant events enables background scripts to lie dormant until those events are fired and prevents the extension from missing essential triggers. Listeners must be registered synchronously from the start of the page.
Moreover, it usually works for a while, even with the background script being unloaded. It takes a while for the described behavior to manifest, and as soon as it does, it happens on every click.
Of course, I could catch the error, wait a bit, and retry - but I’d like to know what’s the recommended approach here.
Thanks, any hint would be much appreciated,
Philipp