How to remove PWA service worker and its cache from client browser after remove PWA in angular 6 website

11,345

Solution 1

The code you used is correct to unregister the service worker and delete its cache from the client.

Is your SW processing any long run tasks? Because if so, it will wait to complete that task before being removed.

In the worst scenario, your service worker will check within 24 hours if a newer version is available. This feature is called fail safe and will be triggered by the browser.

Your code is already good, but if you want to read more about Service Workers and caching strategies, I wrote an article about them.

Solution 2

The browser will disable the service worker after its lifetime.

I have faced this issue once and it was really painful.

Hack: In your app.component.ts use the following line inside ngAfterViewInit();

ngAfterViewInit() {
   window.location.reload(); 
}

This is a dirty hack not a bad practice keep this code live for few days until you know that your users have the latest version of your angular-app.

After that if you wish to use Service-Workers for PWA Use the following code to automatically update your client.

Inject private swUpdate: SwUpdate, private snackbar: MatSnackBar in constructor and write the following code inside it.

this.swUpdate.available.subscribe(evt => {
        let snack = this.snackbar.open('Update Available', 'Reload Please.');

        snack.onAction().subscribe(() => {
            window.location.reload();
        });

        setTimeout(() => {
            snack.dismiss();
        }, 10000);
    });

If you still face any problem let me know that can be an interesting problem to solve.

Share:
11,345
Rajdip Khavad
Author by

Rajdip Khavad

Updated on June 29, 2022

Comments

  • Rajdip Khavad
    Rajdip Khavad almost 2 years

    I have added PWA features and service worker to my angular website. After the release to the live server many user started getting issues, like: "This Site Can't Be Reached", but when user clicks CTRL+ F5 then it works fine.

    For immediate solution I have removed the PWA and service worker from my release. Nevertheless many users are facing the same issue or "index page not found" error from service worker.

    How can I remove or unregister the old service worker from the end user's browser?

    I tried this code to remove the service worker cache :

    if ('caches' in window) {
        caches.keys()
          .then(function(keyList) {
              return Promise.all(keyList.map(function(key) {
                  return caches.delete(key);
              }));
          })
    }
    

    To remove the service worker I have added the following:

    if(window.navigator && navigator.serviceWorker) {
      navigator.serviceWorker.getRegistrations()
      .then(function(registrations) {
        for(let registration of registrations) {
          registration.unregister();
        }
      });
    }