42 lines
1.0 KiB
JavaScript
42 lines
1.0 KiB
JavaScript
/* 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);
|
|
}),
|
|
);
|
|
});
|