0

I'm currently stumped on a problem where the content script will send a message before the service worker becomes ready after being inactive for a while.

The error message is "The message port closed before a response was received."

There are actually 3 windows opened to replicate it.

  1. chrome://serviceworker-internals/
  2. chrome://extensions/ (with Service worker inactive)
  3. Tab where the content script containing a button that will send a message to service worker.

When i press the button to send message from content script to service worker, the "running status" of the service worker in chrome://serviceworker-internals/ was still "starting" before it eventually goes to "running".

It seems like the message is sent before the status is completely running.

Is there any way to handle this type of scenario?

The.Wolfgang.Grimmer
  • 1,172
  • 2
  • 9
  • 32
  • 1
    The service worker automatically wakes up, there's no need to wait or handle this in any way, so there must be either a bug in Chrome or a mistake in your code. – wOxxOm Feb 22 '23 at 12:15
  • I'm aware of this as well, that's why i'm perplexed of this issue. It actually wakes up the Service worker but it is not yet active the time the message was sent by the content script. I actually have `chrome://serviceworker-internals/` opened on 1 window, and the Service worker is still on "Starting" process when I press a button on my extension to send a message to background script. – The.Wolfgang.Grimmer Feb 23 '23 at 00:43
  • Then it's a bug in Chrome, one of the many in ManifestV3. Don't use it. – wOxxOm Feb 23 '23 at 11:10
  • Is there a way to trigger skip waiting in service worker in background script? If so, are there any drawbacks doing it? – The.Wolfgang.Grimmer Feb 27 '23 at 00:32
  • I guess you mean "skip waiting" in devtools Application panel after you reload the extension, in which case it's a bug in Chrome because reloading *must* terminate all the currently running scripts of the extension. – wOxxOm Feb 27 '23 at 00:59
  • Yeah, upon researching it seems like you can trigger it will self.skipWaiting(). Similar to this link: https://dev.to/gelopfalcon/service-worker-and-its-self-skipwaiting-44o5. The thing with the current issue is that we have to do some initialization that returns a Promise before we attach the chrome.runtime.onMessage listeners. I think this is somehow relevant to the fundamental issue of not registering event handlers asynchronously, but we depend on values that must be initialized first that are used in onMessage listener. – The.Wolfgang.Grimmer Feb 27 '23 at 01:05
  • Then it's a mistake in your code because listeners must be added synchronously in order for the browser to wake up the SW properly. You can store the promise in a variable, add the listener, then wait for the promise to settle inside the listener, [example](/a/73090402). – wOxxOm Feb 27 '23 at 12:47

0 Answers0