loading...

React Service worker: Load new content without forcing the user to close the tab ?

shubhamak2 profile image shubhamak2 ・2 min read

I'm working on implementing the service worker concept in react and I have added all the configurations suggested in the Link https://create-react-app.dev/docs/making-a-progressive-web-app/ but the problem here is that for displaying the new content (when the network changed from offline to online), I've to display user to message like 'New content is available once existing tabs are closed.' So here we're forcing the user to close the page for displaying new content. Even the refresh option is also not working here.

Check the below method - (This is a method created when we build react app using create-react-app, the method can be found in react-app/service-worker.js)

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.
              console.log(
                'New content is available and will be used when all ' +
                  'tabs for this page are closed. See'
              );

              // 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);
    });
}
Enter fullscreen mode Exit fullscreen mode

You can clearly see the console

New content is available and will be used when all tabs for > this page are closed.

What is the best way to achieve this? So only refreshing the page, we can update the previously stored cache.

Posted on by:

Discussion

pic
Editor guide