Add push notif handling (clicks and push events)

This commit is contained in:
Gigiaj 2025-06-08 20:07:24 -05:00
parent 1d4864592f
commit c77ba1b534

View file

@ -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();