53 lines
1.6 KiB
JavaScript
53 lines
1.6 KiB
JavaScript
// Service Worker — Sargasse-Sentry
|
|
// fetch handler requis par Chrome pour le critère d'installabilité PWA
|
|
self.addEventListener('fetch', (event) => {
|
|
// Pass-through : on ne met rien en cache pour l'instant (app data-driven, pas offline)
|
|
event.respondWith(fetch(event.request));
|
|
});
|
|
|
|
self.addEventListener('push', (event) => {
|
|
if (!event.data) return;
|
|
|
|
let payload;
|
|
try {
|
|
payload = event.data.json();
|
|
} catch {
|
|
payload = { title: 'Alerte sargasses', body: event.data.text() };
|
|
}
|
|
|
|
const title = payload.title ?? 'Alerte sargasses';
|
|
const options = {
|
|
body: payload.body ?? '',
|
|
icon: '/icons.svg',
|
|
badge: '/icons.svg',
|
|
tag: payload.spotId ? `sargasse-${payload.spotId}` : 'sargasse-alert',
|
|
renotify: true,
|
|
data: { url: payload.url ?? '/' },
|
|
};
|
|
|
|
event.waitUntil(self.registration.showNotification(title, options));
|
|
});
|
|
|
|
self.addEventListener('notificationclick', (event) => {
|
|
event.notification.close();
|
|
|
|
const rawUrl = event.notification.data?.url ?? '/';
|
|
// N'autoriser que les URLs relatives ou du même domaine (protection open redirect)
|
|
const targetUrl = (rawUrl.startsWith('/') || rawUrl.startsWith(self.location.origin))
|
|
? rawUrl
|
|
: '/';
|
|
|
|
event.waitUntil(
|
|
clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windowClients) => {
|
|
for (const client of windowClients) {
|
|
if (client.url === targetUrl && 'focus' in client) {
|
|
return client.focus();
|
|
}
|
|
}
|
|
if (clients.openWindow) {
|
|
return clients.openWindow(targetUrl);
|
|
}
|
|
})
|
|
);
|
|
});
|