34 lines
1.1 KiB
JavaScript
34 lines
1.1 KiB
JavaScript
// sw.js — service worker for the notification + push test page.
|
|
|
|
self.addEventListener('install', () => self.skipWaiting());
|
|
self.addEventListener('activate', (event) => event.waitUntil(self.clients.claim()));
|
|
|
|
// Server-sent push lands here even when every tab is closed.
|
|
self.addEventListener('push', (event) => {
|
|
const data = event.data ? event.data.json() : {};
|
|
event.waitUntil(
|
|
self.registration.showNotification(data.title || 'Push', {
|
|
body: data.body || '',
|
|
icon: 'https://dummyimage.com/192x192/47a/fff.png&text=%E2%86%93',
|
|
vibrate: [120, 60, 120],
|
|
tag: 'push'
|
|
})
|
|
);
|
|
});
|
|
|
|
// Handle taps on the notification or its action buttons.
|
|
self.addEventListener('notificationclick', (event) => {
|
|
const action = event.action; // '', 'open', or 'dismiss'
|
|
event.notification.close();
|
|
if (action === 'dismiss') return;
|
|
|
|
event.waitUntil(
|
|
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((windows) => {
|
|
for (const win of windows) {
|
|
if ('focus' in win) return win.focus();
|
|
}
|
|
if (self.clients.openWindow) return self.clients.openWindow('/');
|
|
})
|
|
);
|
|
});
|