Search code examples
javascriptreactjsservice-workercreate-react-appprogressive-web-apps

Create-React-App - modify serviceWorker to poll for new updates?


I'm working on adding a requested feature to my SPA. We have some users who leave their tabs open to our application for long periods of time. We also push out frequent updates (sometimes 5x a day, as we're pre-revenue). I'm wondering if it's possible to modify the serviceWorker that comes installed with Create-React-App to run a polling loop (maybe every 10 minutes) to poll for new updates to the application, instead of only on initial page load.

This way, a user who leaves their tab open could receive update notifications without having to refresh.

Has anyone achieved something like this before, and know how I might implement that into the CRA serviceWorker?


Solution

  • Figured it out! In the registerServiceWorker.js file, I added a simple setInterval inside the callback for the navigator.serviceWorker.register() function:

    // poll for live updates to the serviceWorker
    pollingLoopInterval = setInterval(async () => {
        await registration.update();
    }, POLLING_LOOP_MS);
    

    Easy!