Skip to content

Commit 973efc5

Browse files
authored
fix: use pagehide instead of beforeunload for tracking closing pages (#2720)
1 parent 61dd37d commit 973efc5

3 files changed

Lines changed: 25 additions & 23 deletions

File tree

‎src/browser/sources/service-worker-source.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -278,8 +278,12 @@ Please consider using a custom "serviceWorker.url" option to point to the actual
278278
this.#channel.on('RESPONSE', this.#handleResponse.bind(this))
279279

280280
window.addEventListener(
281-
'beforeunload',
282-
() => {
281+
'pagehide',
282+
(event) => {
283+
if (event.persisted) {
284+
return
285+
}
286+
283287
if (worker.state !== 'redundant') {
284288
this.#channel.postMessage('CLIENT_CLOSED')
285289
}

‎src/mockServiceWorker.js‎

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -27,16 +27,29 @@ addEventListener('message', async function (event) {
2727
return
2828
}
2929

30+
if (event.data === 'CLIENT_CLOSED') {
31+
const allClients = await self.clients.matchAll({
32+
type: 'window',
33+
})
34+
35+
activeClientIds.delete(clientId)
36+
37+
const remainingClients = allClients.filter((client) => {
38+
return client.id !== clientId
39+
})
40+
41+
// Unregister itself when there are no more clients
42+
if (remainingClients.length === 0) {
43+
self.registration.unregister()
44+
}
45+
}
46+
3047
const client = await self.clients.get(clientId)
3148

3249
if (!client) {
3350
return
3451
}
3552

36-
const allClients = await self.clients.matchAll({
37-
type: 'window',
38-
})
39-
4053
switch (event.data) {
4154
case 'KEEPALIVE_REQUEST': {
4255
sendToClient(client, {
@@ -70,21 +83,6 @@ addEventListener('message', async function (event) {
7083
})
7184
break
7285
}
73-
74-
case 'CLIENT_CLOSED': {
75-
activeClientIds.delete(clientId)
76-
77-
const remainingClients = allClients.filter((client) => {
78-
return client.id !== clientId
79-
})
80-
81-
// Unregister itself when there are no more clients
82-
if (remainingClients.length === 0) {
83-
self.registration.unregister()
84-
}
85-
86-
break
87-
}
8886
}
8987
})
9088

‎test/browser/msw-api/unregister.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
import type { SetupWorkerApi } from 'msw/browser'
1+
import type { SetupWorker } from 'msw/browser'
22
import { test, expect } from '../playwright.extend'
33

44
declare namespace window {
55
export const msw: {
6-
worker: SetupWorkerApi
6+
worker: SetupWorker
77
}
88
}
99

0 commit comments

Comments
 (0)