// sw.js — Service Worker per Web Push
// DEVE essere servito da https://cottocusimano.com/sw.js con scope '/'
// (o da sottocartella con header Service-Worker-Allowed: /)
self.addEventListener('install', () => self.skipWaiting());
self.addEventListener('activate', (e) => e.waitUntil(self.clients.claim()));
self.addEventListener('push', (event) => {
let data = {};
try { data = event.data ? event.data.json() : {}; } catch { data = {}; }
const title = data.title || 'Nuovo messaggio';
const options = {
body: data.body || '',
icon: data.icon || '/favicon-192.png',
badge: data.badge || '/badge-72.png',
tag: data.tag || 'msg-' + (data.id_ticket || data.id_lotto || Date.now()),
renotify: true,
data: {
url: data.url || '/',
id_ticket: data.id_ticket || null,
id_lotto: data.id_lotto || null
}
};
event.waitUntil(self.registration.showNotification(title, options));
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const targetUrl = event.notification.data && event.notification.data.url
? event.notification.data.url : '/';
event.waitUntil(
self.clients.matchAll({ type: 'window', includeUncontrolled: true })
.then((clientList) => {
// Se una finestra del portale è già aperta, la riusa
for (const client of clientList) {
if (client.url.includes(self.location.origin) && 'focus' in client) {
client.navigate(targetUrl);
return client.focus();
}
}
if (self.clients.openWindow) return self.clients.openWindow(targetUrl);
})
);
});
test