in packages/docusaurus-plugin-pwa/src/registerSw.js [144:220]
async function registerSW() {
const {Workbox} = await import('workbox-window');
const offlineMode = await isOfflineModeEnabled();
const url = createServiceWorkerUrl({offlineMode, debug});
const wb = new Workbox(url);
const registration = await wb.register();
const sendSkipWaiting = () => wb.messageSW({type: 'SKIP_WAITING'});
const handleServiceWorkerWaiting = async () => {
if (debug) {
console.log('[Docusaurus-PWA][registerSw]: handleServiceWorkerWaiting');
}
// Immediately load new service worker when files aren't cached
if (!offlineMode) {
sendSkipWaiting();
} else if (PWA_RELOAD_POPUP) {
const renderReloadPopup = (await import('./renderReloadPopup')).default;
await renderReloadPopup({
onReload() {
wb.addEventListener('controlling', () => {
window.location.reload();
});
sendSkipWaiting();
},
});
}
};
if (debug) {
if (registration.active) {
console.log(
'[Docusaurus-PWA][registerSw]: registration.active',
registration,
);
}
if (registration.installing) {
console.log(
'[Docusaurus-PWA][registerSw]: registration.installing',
registration,
);
}
if (registration.waiting) {
console.log(
'[Docusaurus-PWA][registerSw]: registration.waiting',
registration,
);
}
}
// Update the current service worker when the next one has finished
// installing and transitions to waiting state.
wb.addEventListener('waiting', (event) => {
if (debug) {
console.log('[Docusaurus-PWA][registerSw]: event waiting', event);
}
handleServiceWorkerWaiting();
});
// Update current service worker if the next one finishes installing and
// moves to waiting state in another tab.
wb.addEventListener('externalwaiting', (event) => {
if (debug) {
console.log('[Docusaurus-PWA][registerSw]: event externalwaiting', event);
}
handleServiceWorkerWaiting();
});
// Update service worker if the next one is already in the waiting state.
// This happens when the user doesn't click on `reload` in the popup.
if (registration.waiting) {
await handleServiceWorkerWaiting();
}
}