Skip to content

Commit 91d31da

Browse files
committed
fix: add safe closing broadcast channel in case of error during the push notifications flow
1 parent 83177dd commit 91d31da

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

src/hooks/pushNotifications/useWebPushNotifications.ts

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,21 @@ export function useWebPushNotifications() {
99
const channel = ref<BroadcastChannel | null>(null)
1010
const isSupported = computed(() => typeof BroadcastChannel !== 'undefined')
1111

12+
/**
13+
* Closes the broadcast channel in case of error for preventing memory leaks
14+
*/
15+
const safeCloseChannel = () => {
16+
if (channel.value) {
17+
try {
18+
channel.value.close()
19+
} catch (error) {
20+
console.warn('[Web Push] Error closing BroadcastChannel:', error)
21+
} finally {
22+
channel.value = null
23+
}
24+
}
25+
}
26+
1227
/**
1328
* Gets reference to pushService (always WebPushService on web)
1429
*/
@@ -29,6 +44,7 @@ export function useWebPushNotifications() {
2944
channel.value = new BroadcastChannel('adm_notifications')
3045
} catch (error) {
3146
console.error('[Web Push] Failed to create BroadcastChannel:', error)
47+
channel.value = null
3248
}
3349
}
3450

@@ -43,6 +59,7 @@ export function useWebPushNotifications() {
4359
return true
4460
} catch (error) {
4561
console.error('[Web Push] Failed to send private key to SW:', error)
62+
safeCloseChannel()
4663
return false
4764
}
4865
}
@@ -84,6 +101,7 @@ export function useWebPushNotifications() {
84101
return true
85102
} catch (error) {
86103
console.error('[Web Push] Failed to clear private key:', error)
104+
safeCloseChannel()
87105
return false
88106
}
89107
}
@@ -106,6 +124,7 @@ export function useWebPushNotifications() {
106124
return true
107125
} catch (error) {
108126
console.error('[Web Push] Failed to sync settings:', error)
127+
safeCloseChannel()
109128
return false
110129
}
111130
}
@@ -121,18 +140,14 @@ export function useWebPushNotifications() {
121140
return true
122141
} catch (error) {
123142
console.error('[Web Push] Failed to set message handler:', error)
143+
safeCloseChannel()
124144
return false
125145
}
126146
}
127147

128148
onMounted(setupChannel)
129149

130-
onBeforeUnmount(() => {
131-
if (channel.value) {
132-
channel.value.close()
133-
channel.value = null
134-
}
135-
})
150+
onBeforeUnmount(safeCloseChannel)
136151

137152
return {
138153
isSupported,

0 commit comments

Comments
 (0)