dashboard/sw.js (1698 bytes)
1 // The service worker of the dashboard on a phone. It keeps the page and its icons, so that the app 2 // opens when the tunnel to the server is down. The archive, the prompts, and the memories always 3 // come from the server: a copy of them would show old ideas as if they were current. 4 // 5 // A browser starts a service worker only on https or on localhost, so the page registers it only 6 // there. Without it the page still works; it only needs the network each time. 7 8 const CACHE = 'ideamine-shell-v1'; 9 const SHELL = ['./', './manifest.webmanifest', './icon-192.png', './icon-512.png', './icon-maskable-512.png', './apple-touch-icon.png']; 10 11 self.addEventListener('install', (event) => { 12 event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(SHELL)).then(() => self.skipWaiting())); 13 }); 14 15 self.addEventListener('activate', (event) => { 16 event.waitUntil( 17 caches.keys() 18 .then((names) => Promise.all(names.filter((name) => name !== CACHE).map((name) => caches.delete(name)))) 19 .then(() => self.clients.claim()), 20 ); 21 }); 22 23 const live = (url) => url.pathname.endsWith('/data.json') || url.pathname.includes('/api/') || url.pathname.includes('/v1/'); 24 25 self.addEventListener('fetch', (event) => { 26 const url = new URL(event.request.url); 27 if (event.request.method !== 'GET' || url.origin !== self.location.origin || live(url)) return; // the server answers 28 event.respondWith( 29 fetch(event.request) 30 .then((response) => { 31 const copy = response.clone(); 32 caches.open(CACHE).then((cache) => cache.put(event.request, copy)); 33 return response; 34 }) 35 .catch(() => caches.match(event.request).then((hit) => hit || caches.match('./'))), 36 ); 37 });