Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/browser/sources/service-worker-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
}
Expand Down
36 changes: 17 additions & 19 deletions src/mockServiceWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand Down Expand Up @@ -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
}
}
})

Expand Down
4 changes: 2 additions & 2 deletions test/browser/msw-api/unregister.test.ts
Original file line number Diff line number Diff line change
@@ -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
}
}

Expand Down
Loading