I'm making my website offline first with service worker. I want to prompt user to refresh the page when updated content is available. I want users to know that they are viewing outdated contend, so they can get latest content by refreshing the page.
These implementations are a good example:
Approach #3 in this article.
I am using cache-first service worker provided by PWABuilder. It works well, but it does not prompt the user of available updates.
I have tried to copy the code from the articles above, but couldn't get it to work.
Here is the repo of the service worker I currently use.
The code I am trying to add to the service worker script:
addEventListener('message', messageEvent => {
if (messageEvent.data === 'skipWaiting') return skipWaiting();
});
Script I'm trying to add to the webpage:
/ reload once when the new Service Worker starts activating
var refreshing;
navigator.serviceWorker.addEventListener('controllerchange',
function() {
if (refreshing) return;
refreshing = true;
window.location.reload();
}
);
function promptUserToRefresh(reg) {
// this is just an example
// don't use window.confirm in real life; it's terrible
if (window.confirm("New version available! OK to refresh?")) {
reg.waiting.postMessage('skipWaiting');
}
}
listenForWaitingServiceWorker(reg, promptUserToRefresh);
If I just add this code to service worker and webpage respectfully, the service worker functions fine. But update prompt does not work.
I get this error in console:
Uncaught ReferenceError: reg is not defined
at (index):231