1

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:

  1. Service worker demo by Mozilla

  2. 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
Andre
  • 11
  • 2

1 Answers1

0

Well, your problem doesn't necessarily have that much to do with Service Workers :) If you look at the error message (shown in console) carefully, you'll see that it is clearly telling you a variable called reg is not defined. In other words, somewhere in your code you're trying to reference a variable with a name "reg" but "reg" doesn't exist there.

It seems that the code pasted in your question is not the whole thing, but I suspect the problem lies here:

listenForWaitingServiceWorker(reg, promptUserToRefresh);

Anyhow, the error message tells you the problem occurs at line 231 in your html file so check that out.

pate
  • 4,937
  • 1
  • 19
  • 25
  • Thanks. I don't know javascript well enough to fix it my self. I managed to create PWA capable static site with hugo following tutorials, but I cant really code. Hope I can get some help here. – Andre Jun 13 '19 at 13:15