When should a service worker self destruct?

630 Views Asked by At

I found this repo describing HOW to destroy a service worker. But I didn't find any resources describing WHEN a worker should destroy/uninstall/unregister itself.

When I develop websites, I often use port 8080. I can be working on site X that has a service worker, then work on site Y that doesn't have a service worker but the original and now incorrect service worker persists.

The logic for a service worker deciding to uninstall itself is a bit tricky because we want to:

  • Allow the service worker to work offline.
  • Allow the service worker to survive a captive wifi portal.
  • Detect the browser is online but this site should not have a service worker, or that the service worker should be a different one.

Is there a standard mechanism or convention around this?

2

There are 2 best solutions below

4
David Bradshaw On

The simple answer is that normally it would never destroy itself.

This seems to be a problem for you as you are developing multiple sites and then testing them all as localhost:8080.

Their are a few ways to address this particular problem:

The first would be to set up aliases for each site you develop in /etc/hosts.

127.0.0.1  local.site-a.com
127.0.0.1  local.site-b.com

Another option is to configure each project to run on a different port when testing.

The last option would be to include the code you linked to in your question, in each project that does not have a service worker. Although would this approach you would then ideally need to make your build process only include it in Dev builds.

3
Akash Badam On

you have to register a javascript file in serviceworker which checks the local path of site X before running your javascript file.

navigator.serviceWorker.register('/checking.js').then(function(registration) {
  // Registration was successful
  }

In checking.js

if(window.location.href == "YOUR X SITE FILE PATH"){
 //Run the javascript file which you have created for site X 
}

Remember during production you have to change the parameter of serviceWorker() to your respective js file