Skip to content

Commit

Permalink
Unregister active service workers on hard reload
Browse files Browse the repository at this point in the history
  • Loading branch information
ljwagerfield committed Jul 4, 2024
1 parent 1cf1bd8 commit 37df4c7
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/private/ServiceWorkerUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,10 +130,17 @@ export class ServiceWorkerUtils<TMessage> {
}

private async getActiveServiceWorker(serviceWorkerScope: string): Promise<ServiceWorker | undefined> {
// 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;
}
}
}

Expand Down

0 comments on commit 37df4c7

Please sign in to comment.