Unregister service workers in Safari

By

Learn how to unregister a service worker in Safari on macOS, where there is no DevTools button, by running navigator.serviceWorker.getRegistrations in console.

~~~

To unregister a service worker in Safari on macOS, you run a snippet of JavaScript in the browser console. There’s no button for it.

You can easily unregister a service worker in Chrome, from the Application tab in the DevTools. Safari’s developer tools don’t offer that, so we do it manually.

First you need access to the browser console. If you don’t see a Develop menu in Safari’s menu bar, enable it in Safari’s settings, in the Advanced tab. Then open the console from the Develop menu, or press Option-Cmd-C.

With the site open, run this JS in the console:

navigator.serviceWorker.getRegistrations()
  .then(registrations => {
    registrations.map(r => {
      r.unregister()
    })
  })

getRegistrations() returns a promise that resolves with all the service worker registrations for the current origin. We loop over them and call unregister() on each one.

How do you know it worked?

Run getRegistrations() again and inspect the result:

navigator.serviceWorker.getRegistrations()
  .then(registrations => console.log(registrations))
//[]

An empty array means no service workers are registered for the site.

Why would you need this?

Service workers intercept network requests and can serve cached responses. When you’re debugging a site and keep seeing stale content, an old service worker is a common suspect. Unregistering it puts the browser back in a clean state.

The worker comes back after a reload

Be careful with one thing: unregistering doesn’t stop the page from registering the worker again. If the site’s code calls navigator.serviceWorker.register() on load, a reload brings the worker right back.

That’s expected. If you’re debugging your own site, remove or comment out the registration call first, then unregister. If it’s someone else’s site, do your testing in the same session, before reloading.

Also note that unregister() removes the worker, not the caches it created. Data stored through the Cache API stays on disk. To wipe that too, run this in the console:

const keys = await caches.keys()
keys.map(k => caches.delete(k))

After that, the site starts from scratch: no worker, no caches.

~~~

Related posts about platform: