Refresh Service Worker

Have you ever enabled a service worker and then realised that your updates are not showing because of caching. I have.

According to MDN a service worker will update every 24 hour or so or when all pages/instances are closed.

This can be a problem if you have made recent changes or the website is added to home screen. There could be reasons not to force update the service worker whenever a new one is available, so a better solution is to prompt the user to update (if they want to).

How to detect when a new worker is available

There are two parts to manage this. The service worker must listen for messages from the browser (client refreshing), and the browser must listen for new service workers.

Service worker

To listen for messages inside the service worker we need to add an event listener for the message event.

In my solution I send an object to the service worker with an action property. So when the service worker receives action: 'skipWaiting' it knows to activate the pending worker.