Keith
Keith

Reputation: 155662

Is there a way to tell in the page that a service worker has recently upgraded?

I have a SPA with a service worker.

I don't want to force users to update, so usually the new worker updates in the background, but I notify users and they can click a button to message the worker to skipWaiting. When this happens I rely on oncontrollerchange to force any other tabs they have open to refresh.

I want to show a link to release notes after the worker has upgraded, either due to refresh of all tabs or they force the refresh.

However, I don't want to show these notes the first time they visit, or every time the service worker activates. If they don't read the release notes I don't want to keep nagging them about it.

Is there an event or reliable design pattern I can use to tell (in the page) that the service worker has updated to a new version?

Upvotes: 2

Views: 51

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

A straightforward solution would be to add a query parameter to the current URL, and instead of calling location.reload() to reload your page, instead change the location value to that URL.

Something like:

// Inside your `controllerchange` listener, call reloadWithNotes()
function reloadWithNotes() {
  const url = new URL(location.href);
  url.searchParams.set('showNotes', '');
  location = url.href;
}

// Elsewhere...
window.addEventListener('load', () => {
  const url = new URL(location.href);
  if (url.searchParams.has('showNotes')) {
    // Show your release notes.

    // Remove the parameter.
    url.searchParams.delete('showNotes');
    window.history.replaceState({}, document.title, url.href);
  }
});

Upvotes: 1

Related Questions