I believe this entire discussion was able to encompass a lot of useful information, and solutions for some problems that have been noted, so I think there isn’t much that can be discussed around this any longer and I’ll write down the important stuff.
- Content-script communication to Background-script communication via Port messaging can be done even if the Background-script is stopped
- As long as the Content-script connects via
browser.runtime.connect(...)
(if not already connected) before sending a message then the Background-script will always wake up to receive it
- As long as the Content-script connects via
- Always put any listeners at the top of the Background-script
- If there is any logic that works before the listeners, rework/redesign that logic order and start with the listeners first and only then do the rest if possible.
- If that is not possible, and the extension requires the background script to be always running, we can make use of an API heartbeat to keep it alive for as long as it is needed
- For example, if the extension only needs the Background-script to stay alive while a Content-script exists, that Content-script can send messages to the Background-script via Port messaging every 10s or so
- Another example, if the extension needs the Background-script to stay alive regardless, the extension can implement a ghost (iframe) page that does the same thing as the example above
I used the example of Port messaging as a way to keep the Background-script running due to frequent API activity, but it is possible a different API can be used. I personally used that one only so far, and I have not yet explored other options, but it is possible that, for example, changing the local storage can have the same effect, just be aware that what works for Firefox might not work for Chrome if you’re building a cross-browser extension:
One thing was made very clear; Firefox/Mozilla needs to improve their documentation a bit more if they want more devs to adopt MV3, these are important aspects that should by no means be only available in sparse footnotes with no clear examples, or guidance (top-level listeners, keep alive techniques, etc.).
Thanks everyone for all the help and contributing to the discussion.