| 1 | 'use strict'; |
| 2 | // No page/API cache: authenticated games must always come from the server. |
| 3 | self.addEventListener('install', event => event.waitUntil(self.skipWaiting())); |
| 4 | self.addEventListener('activate', event => event.waitUntil(self.clients.claim())); |
| 5 | self.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((async () => |
| 11 | { |
| 12 | // Skip OS notifications while the player is already looking at Microchess. |
| 13 | const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); |
| 14 | if (windows.some(client => client.visibilityState === 'visible')) return; |
| 15 | await self.registration.showNotification('Microchess', { |
| 16 | body: typeof data.body === 'string' ? data.body : 'A game is waiting for you.', |
| 17 | icon: new URL('assets/app-icon-192.png', self.registration.scope).href, |
| 18 | tag: game ? `game-${game}` : 'microchess', |
| 19 | data: { game } |
| 20 | }); |
| 21 | })()); |
| 22 | }); |
| 23 | self.addEventListener('notificationclick', event => |
| 24 | { |
| 25 | event.notification.close(); |
| 26 | const url = new URL('./', self.registration.scope); |
| 27 | const game = event.notification.data?.game; |
| 28 | if (Number.isSafeInteger(game) && game > 0) url.searchParams.set('game', game); |
| 29 | event.waitUntil((async () => |
| 30 | { |
| 31 | const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); |
| 32 | // Navigate the existing app window through the normal login/main-screen flow. |
| 33 | const existing = windows.find(client => client.url.startsWith(self.registration.scope)); |
| 34 | if (existing) { |
| 35 | try { const navigated = await existing.navigate(url.href); if (navigated) return await navigated.focus(); } catch (_) {} |
| 36 | } |
| 37 | return self.clients.openWindow(url.href); |
| 38 | })()); |
| 39 | }); |
projects-timfalken-com microchess