diff --git a/packages/cra-template-pwa-typescript/template/src/serviceWorkerRegistration.ts b/packages/cra-template-pwa-typescript/template/src/serviceWorkerRegistration.ts index efbf2ac..77a8cf7 100644 --- a/packages/cra-template-pwa-typescript/template/src/serviceWorkerRegistration.ts +++ b/packages/cra-template-pwa-typescript/template/src/serviceWorkerRegistration.ts @@ -95,6 +95,26 @@ function registerValidSW(swUrl: string, config?: Config) { } }; }; + + // in the case a page is loaded an a service worker is already waiting + // we should trigger the onUpdate callback + const waitingWorker = registration.waiting; + if (waitingWorker) { + if (navigator.serviceWorker.controller && waitingWorker.state === 'installed') { + // 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 https://cra.link/PWA.' + ); + + // Execute callback + if (config && config.onUpdate) { + config.onUpdate(registration); + } + } + } }) .catch((error) => { console.error('Error during service worker registration:', error); diff --git a/packages/cra-template-pwa/template/src/serviceWorkerRegistration.js b/packages/cra-template-pwa/template/src/serviceWorkerRegistration.js index 2262ecd..94f6746 100644 --- a/packages/cra-template-pwa/template/src/serviceWorkerRegistration.js +++ b/packages/cra-template-pwa/template/src/serviceWorkerRegistration.js @@ -90,6 +90,26 @@ function registerValidSW(swUrl, config) { } }; }; + + // in the case a page is loaded an a service worker is already waiting + // we should trigger the onUpdate callback + const waitingWorker = registration.waiting; + if (waitingWorker) { + if (navigator.serviceWorker.controller && waitingWorker.state === 'installed') { + // 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 https://cra.link/PWA.' + ); + + // Execute callback + if (config && config.onUpdate) { + config.onUpdate(registration); + } + } + } }) .catch((error) => { console.error('Error during service worker registration:', error);