Search code examples
reactjscachingservice-workercreate-react-app

React & Service Worker - Cached Content - Inform user


I have a question regarding service workers and reactjs.

The recommendation is to inform the user about cached content or when new content is available, so that the user knows about cached content.

My question is now, how can I inform the user?

When I use create-react-app, in the registerServiceWorker.js there is this code, where it says:

At this point, the old content will have been purged and the fresh content will have been added to the cache. It's the perfect time to display a "New content is available; please refresh." message in your web app.

function registerValidSW(swUrl) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the old content will have been purged and
              // the fresh content will have been added to the cache.
              // It's the perfect time to display a "New content is
              // available; please refresh." message in your web app.
              console.log('New content is available; please refresh.');
            } 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.');
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}

But actually on this script, of course, I do not have access to the document, because the service worker works away from the script. How can I handle this in an react component?

How do others handle this issue and inform the user?


Solution

  • The code included in your question runs inside the context of the window client. You have full control over showing whatever UI elements you'd like. Feel free to modify those console.log() statements and display something instead.

    (There's separate code that runs in the context of the service worker, and you're correct that that code doesn't have access to the DOM. But that's not the code you're asking about.)