PointTracker/public/service-worker.js
2025-01-17 14:06:07 -05:00

46 lines
1.3 KiB
JavaScript

/* public/service-worker.js
Listens to 'push' events and shows a notification.
This file MUST be served via HTTPS or on localhost.
*/
self.addEventListener('push', function(event) {
if (!event.data) {
return;
}
const payload = event.data.json(); // {title, body}
const title = payload.title || 'Timer Notification';
const body = payload.body || 'Time is up!';
const options = {
body: body,
icon: '/icon.png', // optional
badge: '/badge.png' // optional
// any other notification options
};
event.waitUntil(
self.registration.showNotification(title, options)
);
});
// Handle notification click
self.addEventListener('notificationclick', function(event) {
event.notification.close();
// Focus or open the site
event.waitUntil(
clients.matchAll({ type:'window' }).then( windowClients => {
// if we already have a window open, focus it
for (let client of windowClients) {
if (client.url.includes('/PointTracker') && 'focus' in client) {
return client.focus();
}
}
// otherwise, open a new one
if (clients.openWindow) {
return clients.openWindow('/');
}
})
);
});