// Cabin Chat service worker: makes the chat installable as an app, opens the // app from a notification and shows the last loaded page when the router is out // of reach. Network first, so a new version on the router is used right away. // Chat data (cgi-bin) and photos are never cached here. const CACHE = 'cabinchat'; self.addEventListener('install', () => self.skipWaiting()); self.addEventListener('activate', e => e.waitUntil(self.clients.claim())); self.addEventListener('fetch', e => { const req = e.request, url = new URL(req.url); if (req.method !== 'GET' || url.origin !== location.origin || /\/(cgi-bin|img)\//.test(url.pathname)) return; e.respondWith(fetch(req).then(res => { if (res.ok) { const copy = res.clone(); caches.open(CACHE).then(c => c.put(req, copy)); } return res; }).catch(() => caches.match(req, { ignoreSearch: true }) .then(r => r || (req.mode === 'navigate' ? caches.match('./') : Response.error())))); }); self.addEventListener('notificationclick', e => { e.notification.close(); const conv = (e.notification.data || {}).conv || ''; e.waitUntil(self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(list => { for (const c of list) { c.postMessage({ cc: 'open', conv }); return c.focus(); } return self.clients.openWindow('./' + (conv ? '#c=' + conv : '')); })); });