Add service worker for push notifications
This commit is contained in:
@@ -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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user