Progressive web app: check service worker update

Posted on: 2017-08-06

If you stumble on this article it probably means that you are learning how service workers work. If it's the case, I recommend you to start with this great introduction on MDN.

Though you can write your own service worker, I advise you to start with somethng easier like sw-precache, wich is a great librairy that generate a service worker file directly from your static assets list. 😙

Anyway, let's get to what this article is about: manualy check for an update of our service worker.

As you might have read on the MDN guide linked above, the navigator will check for an update of your service worker every 24h or so. But in some case, you may want to check more often, or even provide a way for your users to check for update from your webapp.

If you use sw-precache or have written your own service worker, you've already registered it like this. Instead of the console.log in this file, we can write some code to alert our user that un udpate is available and that they should refresh the page. The most simple thing would be this one line of code :

document.getElementById("app-wrapper").className = "update-available";

With some css, it would be easy to show the "update available" message on the page.

Then what you should do to check manualy for an update is this :

if (`serviceWorker` in navigator) { return navigator.serviceWorker.getRegistration() .then(registration => { if (!registration) { return null; } return registration.update(); }); }

This will get the current service worker registration and tell the navigator to check for an updgrade. Then the event you catch in your service worker registration file (installingWorker.onstatechange) will take be triggered and tell your user to refresh the page ! 😉