push notifications

This commit is contained in:
cpu
2025-03-26 05:04:50 +01:00
parent a0f3489656
commit fc278ed256
4 changed files with 125 additions and 30 deletions

47
sw.js
View File

@@ -148,27 +148,42 @@ self.addEventListener('message', event => {
}
});
self.addEventListener('push', event => {
console.log('[ServiceWorker] Push received');
const data = event.data ? event.data.json() : {};
const title = data.title || 'Game Timer Notification';
const options = {
body: data.body || 'You have a new notification',
icon: '/icons/android-chrome-192x192.png',
badge: '/icons/android-chrome-192x192.png',
data: data
};
event.waitUntil(
self.registration.showNotification(title, options)
);
});
// This helps with navigation after app is installed
self.addEventListener('notificationclick', event => {
console.log('[ServiceWorker] Notification click received');
event.notification.close();
// This looks to see if the current is already open and focuses if it is
// Handle the notification click
event.waitUntil(
self.clients.matchAll({
type: 'window'
})
.then(clientList => {
// Check if there is already a window/tab open with the target URL
for (const client of clientList) {
// If so, just focus it
if (client.url.startsWith(self.location.origin) && 'focus' in client) {
return client.focus();
self.clients.matchAll({ type: 'window' })
.then(clientList => {
for (const client of clientList) {
if (client.url.startsWith(self.location.origin) && 'focus' in client) {
return client.focus();
}
}
}
// If not, open a new window/tab
if (self.clients.openWindow) {
return self.clients.openWindow('/');
}
})
if (self.clients.openWindow) {
return self.clients.openWindow('/');
}
})
);
});