I'm using this well-known pattern for showing a notification when a service worker update is ready to install (this code goes into the web page, it's NOT the service worker code, of course):
// Register service worker.
let newWorker;
if ('serviceWorker' in navigator) {
function showUpdateNotification () {
document.getElementById('updatenotification').style['visibility'] = 'visible';
};
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').then(registration => {
console.log('Service worker registered at scope "' + registration.scope + '".');
// The commented code below is needed to show the notification after a page reload.
//
// if (registration.waiting) {
// console.log('Service working in skipwaiting state.');
// showUpdateNotification();
// }
registration.onupdatefound = () => {
console.log('Service worker update found.');
console.log('Installing service worker is', registration.installing);
newWorker = registration.installing;
newWorker.onstatechange = function () {
console.log('Service worker state changed to', newWorker.state);
if (newWorker.state == 'installed' && navigator.serviceWorker.controller) {
console.log('New service worker is ready to install on refresh.');
showUpdateNotification();
}
};
};
console.log('Updating service worker.');
registration.update();
}).catch(error => console.log('Service worker not registered (' + error +').'))
})
}
Of course, that code works, in the sense that it shows a notification on the web page if a new version of the service worker is ready to be installed.
The problem is that if the page is reloaded at that point, the notification is no longer shown, because if the new service worker is installed and waiting to activate, the updatefound
event is no longer fired.
So, the notification only appears ONCE, when the new service worker is installed and waiting to be activated and start controlling the page, but once the page reloads, the notification is gone.
I've solved that by using the commented code:
// The commented code below is needed to show the notification after a page reload.
//
// if (registration.waiting) {
// console.log('Service working in skipwaiting state.');
// showUpdateNotification();
// }
This code, upon registration, checks if there's some service worker in waiting state and shows, again, the notification.
My question is: is this correct? Can I use that "trick" safely or am I calling trouble?
I'm new to service workers so I'm not sure if I can do this kind of things.
Thanks A LOT in advance.