Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should a service worker self destruct?

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?

like image 842
ubershmekel Avatar asked Dec 30 '19 09:12

ubershmekel


People also ask

How long does a service worker last?

Chrome terminates a SW if the SW has been idle for 30 seconds. Chrome also detects long-running workers and terminates them. It does this if an event takes more than 5 minutes to settle, or if the worker is busy running synchronous JavaScript and does not respond to a ping within 30 seconds.

How do I unregister a service worker?

unregister() The unregister() method of the ServiceWorkerRegistration interface unregisters the service worker registration and returns a Promise .

Should I register service worker on every page?

So, it is sufficient to only call navigator. serviceWorker. register() on your main entry point, and not call it again on any other pages, if you're sure that all users will pass through that entry point at least once. That being said, there's no harm in calling navigator.

What is Service workers in browser?

Service workers are also intended to be used for such things as: Background data synchronization. Responding to resource requests from other origins. Receiving centralized updates to expensive-to-calculate data such as geolocation or gyroscope, so multiple pages can make use of one set of data.


1 Answers

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.

like image 126
David Bradshaw Avatar answered Oct 20 '22 04:10

David Bradshaw