BlueGit

projects-timfalken-com microchess

Files

microchess / web / sw.js

sw.js

sw.js 1.6 KiB Download Raw
1'use strict';
2// No page/API cache: authenticated games must always come from the server.
3self.addEventListener('install', event => event.waitUntil(self.skipWaiting()));
4self.addEventListener('activate', event => event.waitUntil(self.clients.claim()));
5self.addEventListener('push', event =>
6{
7 let data = {};
8 try { data = event.data?.json() || {}; } catch (_) {}
9 const game = Number.isSafeInteger(data.game) && data.game > 0 ? data.game : null;
10 event.waitUntil(self.registration.showNotification('Microchess', {
11 body: typeof data.body === 'string' ? data.body : 'A game is waiting for you.',
12 icon: new URL('assets/app-icon-192.png', self.registration.scope).href,
13 tag: game ? `game-${game}` : 'microchess',
14 data: { game }
15 }));
16});
17self.addEventListener('notificationclick', event =>
18{
19 event.notification.close();
20 const url = new URL('./', self.registration.scope);
21 const game = event.notification.data?.game;
22 if (Number.isSafeInteger(game) && game > 0) url.searchParams.set('game', game);
23 event.waitUntil((async () =>
24 {
25 const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
26 // Navigate the existing app window through the normal login/main-screen flow.
27 const existing = windows.find(client => client.url.startsWith(self.registration.scope));
28 if (existing) {
29 try { const navigated = await existing.navigate(url.href); if (navigated) return await navigated.focus(); } catch (_) {}
30 }
31 return self.clients.openWindow(url.href);
32 })());
33});