diff --git a/src/browser/sources/service-worker-source.ts b/src/browser/sources/service-worker-source.ts index 93046d499..89835e2a1 100644 --- a/src/browser/sources/service-worker-source.ts +++ b/src/browser/sources/service-worker-source.ts @@ -278,8 +278,12 @@ Please consider using a custom "serviceWorker.url" option to point to the actual this.#channel.on('RESPONSE', this.#handleResponse.bind(this)) window.addEventListener( - 'beforeunload', - () => { + 'pagehide', + (event) => { + if (event.persisted) { + return + } + if (worker.state !== 'redundant') { this.#channel.postMessage('CLIENT_CLOSED') } diff --git a/src/mockServiceWorker.js b/src/mockServiceWorker.js index d02b80689..bbf1ad59c 100644 --- a/src/mockServiceWorker.js +++ b/src/mockServiceWorker.js @@ -27,16 +27,29 @@ addEventListener('message', async function (event) { return } + if (event.data === 'CLIENT_CLOSED') { + const allClients = await self.clients.matchAll({ + type: 'window', + }) + + activeClientIds.delete(clientId) + + const remainingClients = allClients.filter((client) => { + return client.id !== clientId + }) + + // Unregister itself when there are no more clients + if (remainingClients.length === 0) { + self.registration.unregister() + } + } + const client = await self.clients.get(clientId) if (!client) { return } - const allClients = await self.clients.matchAll({ - type: 'window', - }) - switch (event.data) { case 'KEEPALIVE_REQUEST': { sendToClient(client, { @@ -70,21 +83,6 @@ addEventListener('message', async function (event) { }) break } - - case 'CLIENT_CLOSED': { - activeClientIds.delete(clientId) - - const remainingClients = allClients.filter((client) => { - return client.id !== clientId - }) - - // Unregister itself when there are no more clients - if (remainingClients.length === 0) { - self.registration.unregister() - } - - break - } } }) diff --git a/test/browser/msw-api/unregister.test.ts b/test/browser/msw-api/unregister.test.ts index 688fdee27..c807b4654 100644 --- a/test/browser/msw-api/unregister.test.ts +++ b/test/browser/msw-api/unregister.test.ts @@ -1,9 +1,9 @@ -import type { SetupWorkerApi } from 'msw/browser' +import type { SetupWorker } from 'msw/browser' import { test, expect } from '../playwright.extend' declare namespace window { export const msw: { - worker: SetupWorkerApi + worker: SetupWorker } }