From 37df4c7035d92037fd00949d0fde731e7837799c Mon Sep 17 00:00:00 2001 From: Lawrence Wagerfield Date: Thu, 4 Jul 2024 10:53:05 +0100 Subject: [PATCH] Unregister active service workers on hard reload --- src/private/ServiceWorkerUtils.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/private/ServiceWorkerUtils.ts b/src/private/ServiceWorkerUtils.ts index af7ab43..0ea722d 100644 --- a/src/private/ServiceWorkerUtils.ts +++ b/src/private/ServiceWorkerUtils.ts @@ -130,10 +130,17 @@ export class ServiceWorkerUtils { } private async getActiveServiceWorker(serviceWorkerScope: string): Promise { + // Existing active Service Workers will not receive 'fetch' events in sessions that start with a hard reload, so + // we must unregister them and register a new one. (See: https://github.com/mswjs/msw/issues/98#issuecomment-612118211) + const isHardReload = navigator.serviceWorker.controller === null; const registrations = await navigator.serviceWorker.getRegistrations(); for (const registration of registrations) { if (registration.active !== null && registration.scope === serviceWorkerScope) { - return registration.active; + if (isHardReload) { + await registration.unregister(); + } else { + return registration.active; + } } }