1

I have a web extension where the content script is communicating with the service worker via browser.runtime.connect({name: 'processor'}) and stores the port as a class field. The service worker listens for new ports and keeps a dictionary to keep track of them and removes them from the list when a disconnect occurs. Both scripts listen for onDisconect and onMessage and both use port.postMessage() to send messages. Neither ever explicitly calls disconnect().

Recently I discovered that the service worker logs have a higher number of log messages for port disconnects than new connections. What I'm seeing is after a new port is registered an onDisconnect for that same port follows almost immediately. However sometimes the port seems to persist and I'll continue to receive messages relating to the corresponding tab. I'll also end up seeing a second call to onDisconnect when I close the tab, but only in situations where other messages keep flowing too. When I handle a disconnect I am removing the port from the dictionary but not unsubscribing from the events, so apparently the object is not getting disposed and is still in use despite the onDisconnect firing?

Additionally, for my current tests, when I open a new tab and navigate to a webpage the issue (sometimes) manifests itself. However if I press F5 to refresh the page then the port doesn't immediately disconnect. Navigating to different webpages first doesn't seem to make a difference, only an explicit refresh seems to change things. Though honestly I'm still fighting to isolate the cause of the behaviors and tests aren't yielding 100% consistent results.

This issue is present in old code that we considered to be working fine, so we're not sure if we somehow missed something or if a change in Chrome may be causing issues?

  • The service worker is not persistent unlike the MV2 background script, [more info](/a/66618269). – wOxxOm Apr 20 '23 at 18:39
  • If it was the service worker shutting down the the service worker wouldn't be maintaining a log during the time when it was shutdown. I also don't think it would be receiving the event if it was the one shutting down the port. Nor do I think the service worker will go inactive after less than a second of inactivity. @wOxxOm – Stephen Teodori Apr 20 '23 at 19:43
  • It may be a bug. There are lots of bugs in ManifestV3 implementation of SW so the workarounds we have to use aren't exactly based on logic. – wOxxOm Apr 20 '23 at 20:52

0 Answers0