Re: [w3c/ServiceWorker] Unregister a service worker when another tab is controlled by it can "resurrect" it (Chrome) (Issue #1687)

> Repro steps:
> 
> * open 2 tabs controlled by the same service worker
> * with the inspector opened, unregister the service worker (or do that in the console if u prefer)
> * the service worker is now flagged as deleted
> * if u just reload 1 of the tab, the reloaded tab will not be controlled, but the service worker is not flagged as deleted anymore
>   
>   * note that it's not like a new service worker is installed, the "id" displayed in the inspector is the same
>   * this is why I say it's resurrected
> 
> This of course makes it hard to properly unregister a service worker unless u reload all the clients. This is what I'm doing, but I wonder if this bug can still happen if a client reload with a bit of delay, leading to the old service worker resurrection.

Hi! If that helps you I've found a way to refresh the SW in all open tabs after it is deregistered.
You send a message command to the service-worker to self-destroy, and the service-worker in turn reloads all controlled clients.

```js
// service-worker code
self.addEventListener('message', ({ data }) => {
 if (data === 'unregister') {
  self.registration.unregister()
   .then(() => self.clients.matchAll())
   .then(clients => clients.forEach(client => client.navigate(client.url)));
 }
});
```

```js
// client code
navigator.serviceWorker.ready.then((registration) => {
     registration.active.postMessage('unregister');
});
```


-- 
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/1687#issuecomment-2059381553
You are receiving this because you are subscribed to this thread.

Message ID: <w3c/ServiceWorker/issues/1687/2059381553@github.com>

Received on Tuesday, 16 April 2024 15:35:00 UTC