Will a `runtime.connect()` port keep a non-persistent background script alive?

I’m looking into non-persistent background scripts, for (improved?) Android support.

The docs say:
“However, a background page does not unload until all visible views and message ports are closed.”

What are “message ports”? Are they the thing that runtime.connect() gives you (which is documented as returning a runtime.Port)? Because if I make such a connection, I see the background script unload* and break my functionality – which depends on the port being connected as long as the content page has a reference to it. ( https://github.com/greasemonkey/greasemonkey/issues/3173#issuecomment-1810597347 ) But the BG script unloading disconnects the port.

* I think! I can’t directly observe this because if I inspect the extension, i.e. to observe a log about the thing unloading, instead Firefox doesn’t unload the non-persistent script. (And logs that this is what it did (not do).) But in this (console open, BG not unloaded) case, my functionality does not break, so I’m pretty confident non-persistent-script-unloading is the cause.

So is an open message/port/connection supposed to prevent unloading the BG script? Is that what the quoted part of the docs are trying to communicate?

1 Like

Good question!
I’ve recently found a similar bug in Chrome where my service worker was unloaded even though I had port opened.

But having port opened is actually not enough (anymore?). At lest in Chrome.
I’ve just got it confirmed here:
So I would say it’s best to keep sending messages through the port to make sure it will stay alive.

Note that you can observe status of your background script here:
(it will say Running/Stopped)

It’s worth noting that this behavior is in line with what Firefox reps have previously discussed regarding Limited Event Pages. One of the main differences between Chromes event pages and limited event pages is that ports must be actively used in order to keep the event page alive.

1 Like

Ok so it seems we agree that the docs are wrong?

Yep, docs need to be updated. I’m working on a couple of updates to extension docs over the next week or so, so I’ll add this to my list.