How to offer a page reload when the service worker is updated after a page refresh?

1.2k Views Asked by At

I'm currently using the latest Workbox version 4.3.1 with workbox-window, I'm offering a page reload for users by listening to the waiting event, I'm using the code provided on the Advanced Recipes page of the Workbox documentation.

The code on the page:

if ('serviceWorker' in navigator) {
  const wb = new Workbox('/sw.js');

  // Add an event listener to detect when the registered
  // service worker has installed but is waiting to activate.
  wb.addEventListener('waiting', (event) => {
    // `event.wasWaitingBeforeRegister` will be false if this is
    // the first time the updated service worker is waiting.
    // When `event.wasWaitingBeforeRegister` is true, a previously
    // updated same service worker is still waiting.
    // You may want to customize the UI prompt accordingly.

    // Assumes your app has some sort of prompt UI element
    // that a user can either accept or reject.
    const prompt = createUIPrompt({
      onAccept: async () => {
        // Assuming the user accepted the update, set up a listener
        // that will reload the page as soon as the previously waiting
        // service worker has taken control.
        wb.addEventListener('controlling', (event) => {
          window.location.reload();
        });

        // Send a message telling the service worker to skip waiting.
        // This will trigger the `controlling` event handler above.
        // Note: for this to work, you have to add a message
        // listener in your service worker. See below.
        wb.messageSW({type: 'SKIP_WAITING'});
      },

      onReject: () => {
        prompt.dismiss();
      }
    })
  });

  wb.register();
}

The code in the service worker file:

self.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
  }
});

I have tested it and it's working just fine, I can show a snackbar to the user and let them know that there's an update and when they accept, a SKIP_WAITING message is sent to the service worker to call skipWaiting().

Let's assume that the user did not accept the reload prompt and refreshed the page or navigated to another page, the new service worker will be kept waiting and won't activate and that's the normal behavior, but my question is how can I show this reload prompt to the user if they refreshed or navigated to another page? It seems that the waiting event is only fired once.

0

There are 0 best solutions below