How to kill a service worker

I’ve repeatedly been confused and thwarted by the forgotten or unexpected existence of an obsolete service worker, so this time I’m writing down how to kill one. The service worker API is relatively complicated and can be difficult to understand.

First of all, you need to know what path the existing service worker is being served from because adding a new service worker at the same path is the only way to overwrite the existing one.

After you’ve found the path (e.g., create a javascript file and put it where ever it needs to go to load at that location.

You can find existing registered service workers in the browser’s dev tools.

Then add the following code to your new service worker.

self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', () =>
    .then(() => self.clients.matchAll())
    .then((clients) => clients.forEach((client) => client.navigate(client.url)))

The very existence of this new file to replace the old service worker script, should install this script as the new service worker, but by default new service workers don’t immediately take over from old service workers.

That’s why we call self.skipWaiting() — that will make this service worker into the active one immediately.

Then, the activate event will fire and in response this new service worker will:’

  1. unregister itself,
  2. find all existing clients (i.e. open pages), and
  3. reload them.

Service worker gone! You can now enjoy hassle free development of your site. 🎉