Skip to content

Commit bc9c026

Browse files
committed
fix: handle CLIENT_CLOSE before !client guard
1 parent 40fa715 commit bc9c026

1 file changed

Lines changed: 19 additions & 9 deletions

File tree

‎src/mockServiceWorker.js‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,6 @@ addEventListener('message', function (event) {
3434

3535
event.waitUntil(
3636
(async () => {
37-
const client = await self.clients.get(clientId)
38-
39-
if (!client) {
40-
return
41-
}
42-
4337
if (event.data === 'CLIENT_CLOSE') {
4438
const allClients = await self.clients.matchAll({
4539
type: 'window',
@@ -64,10 +58,26 @@ addEventListener('message', function (event) {
6458
await self.registration.unregister()
6559
}
6660

67-
await sendToClient(client, {
68-
type: 'CLIENT_CLOSED',
69-
})
61+
const client = await self.clients.get(clientId)
7062

63+
if (client != null) {
64+
await sendToClient(client, {
65+
type: 'CLIENT_CLOSED',
66+
})
67+
}
68+
69+
return
70+
}
71+
72+
/**
73+
* @note Check for the client AFTER handling "CLIENT_CLOSE".
74+
* This prevents early return on "!client" in case the page has reloaded
75+
* and disassociated itself from the worker. This ensures self-unregistration
76+
* still fires for those pages.
77+
*/
78+
const client = await self.clients.get(clientId)
79+
80+
if (!client) {
7181
return
7282
}
7383

0 commit comments

Comments
 (0)