Add service worker for push notifications

This commit is contained in:
2026-03-11 20:46:49 -07:00
parent 7b5187eb93
commit c35c20faeb
+41
View File
@@ -0,0 +1,41 @@
/* eslint-disable no-restricted-globals */
self.addEventListener('push', (event) => {
if (!event.data) return;
try {
const payload = event.data.json();
const options = {
body: payload.body,
icon: payload.icon || '/favicon.ico',
badge: '/favicon.ico',
data: { url: payload.url || '/' },
};
event.waitUntil(self.registration.showNotification(payload.title, options));
} catch {
// Silently fail
}
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const url = event.notification.data?.url || '/';
event.waitUntil(
self.clients
.matchAll({ type: 'window', includeUncontrolled: true })
.then((clientList) => {
// Focus existing window if available
for (const client of clientList) {
if (client.url.includes(self.location.origin)) {
client.navigate(url);
return client.focus();
}
}
// Otherwise open new window
return self.clients.openWindow(url);
}),
);
});