update PWA react app (using CRA) with user clicked button through service worker

Viewed 180

I want to update PWA application when new content is available. Since we can't access DOM from service worker, how can I exactly do that? The service worker correctly recognize the new content, but I can't bind a hook or context to show my modal or update button in react. Any help?

service worker register and onUpdate function:

function RegisterValidSW(swUrl, config) {
 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.
          // setUpdate(true);
          // registration.waiting.postMessage({ type: 'SKIP_WAITING' });
          console.log(
            'New content is available and will be used when all ' +
            'tabs for this page are closed. See https://cra.link/PWA.'
          );

          // 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.');

          // Execute callback
          if (config && config.onSuccess) {
            config.onSuccess(registration);
          }
        }
      }
    };
  };
})
.catch((error) => {
  console.error('Error during service worker registration:', error);
});
}

this function is in the serviceWorkerRegistration.js file. We can add registration.waiting.postMessage({ type: 'SKIP_WAITING' }); function to call skipWaiting but it doesn't wait for user interaction and can't reload the page. how can I solve that?

1 Answers

You can try passing in an onUpdate function when you register the service worker. In that function send a SKIP_WAITING message to the service worker followed a page reload.

 onUpdate: (registration) => {
    console.log("SW: sending SKIP_WAITING message to get updated serviceworker to take effect now (without manual restart)")
    // Old serviceworker will be stopped/new serviceworker started without reload
    registration.waiting.postMessage({type: 'SKIP_WAITING'})
    window.location.reload()
}

Your server worker should have SKIP_WAITING message hander. Something like this:

self.addEventListener('message', (event) => {
console.log("SW: received message event = "+JSON.stringify(event))
if (event.data && event.data.type === 'SKIP_WAITING') {
    self.skipWaiting();
}});

This is working for me.

What I am still struggling with is how to get the app updated if the user leaves the app open. As in,

  1. User browses to PWA url
  2. User adds to Home Screen
  3. User closes browser tab
  4. User opens PWA from Home Screen

and just leaves it open forever and ever...

This should probably go in a new question, but I thought it might be relevant to your use case.

Related