I'd like to show my user that an update is available. Therefore I need to know how to check if he already uses the latest version.
Currently I set an item in localStorage called "updateAvailable" as soon as the serviceWorker tells me that there is a new version available. That works fine.
What doesn't work fine although is when I'd like to set "updateAvailable" to false. The item isn't set in localStorage.
How do I set this item in localStorage when the latest version of my PWA is used?
function registerValidSW(swUrl: string, config?: Config) {
console.log("test 5")
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See [hidden link]'
);
localStorage.setItem("updateAvailable", "true")
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
localStorage.setItem("updateAvailable", "false")
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
that code block only executes in the 'onupdatefound' event.