From c77ba1b5342535c22df2789939c0239596769a91 Mon Sep 17 00:00:00 2001 From: Gigiaj Date: Sun, 8 Jun 2025 20:07:24 -0500 Subject: [PATCH] Add push notif handling (clicks and push events) --- src/sw.ts | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/src/sw.ts b/src/sw.ts index 16ee5de5..ac86f622 100644 --- a/src/sw.ts +++ b/src/sw.ts @@ -73,3 +73,80 @@ self.addEventListener('fetch', (event: FetchEvent) => { })() ); }); + +const onPushNotification = async (event: PushEvent) => { + let title = 'New Notification'; + const options: NotificationOptions = { + body: 'You have a new message!', + icon: DEFAULT_NOTIFICATION_ICON, + badge: DEFAULT_NOTIFICATION_BADGE, + data: { + url: self.registration.scope, + timestamp: Date.now(), + }, + // tag: 'cinny-notification-tag', // Optional: Replaces existing notification with same tag + // renotify: true, // Optional: If using tag, renotify will alert user even if tag matches + // silent: false, // Optional: Set to true for no sound/vibration. User can also set this. + }; + + if (event.data) { + try { + const pushData = event.data.json(); + title = pushData.title || title; + options.body = options.body ?? pushData.data.toString(); + options.icon = pushData.icon || options.icon; + options.badge = pushData.badge || options.badge; + + if (pushData.image) options.image = pushData.image; + if (pushData.vibrate) options.vibrate = pushData.vibrate; + if (pushData.actions) options.actions = pushData.actions; + options.tag = 'Cinny'; + if (typeof pushData.renotify === 'boolean') options.renotify = pushData.renotify; + if (typeof pushData.silent === 'boolean') options.silent = pushData.silent; + + if (pushData.data) { + options.data = { ...options.data, ...pushData.data }; + } + if (typeof pushData.unread === 'number') { + await self.navigator.setAppBadge(pushData.unread); + } else { + await navigator.clearAppBadge(); + } + } catch (e) { + const pushText = event.data.text(); + options.body = pushText || options.body; + } + } + + return self.registration.showNotification(title, options); +}; + +self.addEventListener('push', (event: PushEvent) => event.waitUntil(onPushNotification(event))); + +self.addEventListener('notificationclick', (event: NotificationEvent) => { + event.notification.close(); + + /** + * We should likely add a postMessage back to navigate to the room the event is from + */ + const targetUrl = event.notification.data?.url || self.registration.scope; + + event.waitUntil( + self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => { + for (const client of clientList) { + if (client.url === targetUrl && 'focus' in client) { + return (client as WindowClient).focus(); + } + } + if (self.clients.openWindow) { + return self.clients.openWindow(targetUrl); + } + return Promise.resolve(); + }) + ); +}); + +if (self.__WB_MANIFEST) { + precacheAndRoute(self.__WB_MANIFEST); +} +cleanupOutdatedCaches();