How to unregister and remove old service worker?

Viewed 9574

I have register a service woker using .register and can see in Application tab in dev tool. now my questionn is how to unregister this service worker.

I have run this script

if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
                console.group('====SW registration=======');
                navigator.serviceWorker.register('/sw.js', {scope: './'}).then(function(registration) {
                    console.log('SW registratered successfully');
                    console.log(registration);
                    registration.unregister().then(function(result) {
                        console.log('Unregistered done', result);
                    });
                }).catch(function(error){
                    console.error('sw registration failed', error);
                });
                console.groupEnd();
        });
}

But I see that by doing this, we are actually first registering the service worker and then unregister it. This seems not the correct way to me.

Alternatively, I can click on unregister link near to the service worker from dev tools Application > Service Workers and also click on Application >Clear Storage and re-open the URL in the new tab.

but when I check through chrome://serviceworker-internals/

it displays the list of old and unregistered service worker at bottom of list ( see image)

unregistered sw

So why I am seeing the redundant service worker list here? when will it update? does this is the default behaviour of chrome browser.

2 Answers

You should specify why you want to unregister the Service Worker.

I suppose there are two possibilities:

  • You want to get rid off the /service-worker.js file and remove SW completely
  • You want to have a new/updated SW and replace the previous one

First case: Checkout this answer: How do I uninstall a Service Worker?

Second case: You don't have to unregister the old SW, you just update the code in /service-worker.js and register it on top of the old one. This is the usual scenario. The new, updatet SW will takeover and the obsolete will go away. I suggest you read these tutorials very carefully: https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/lifecycle https://developers.google.com/web/fundamentals/getting-started/primers/service-workers

I'm stressing carefully since it's very easy to get SW related stuff wrong and completely bork your website :)

Related