|
| 1 | +/* PWA service worker */ |
| 2 | + |
| 3 | +const swconfPath = '/assets/js/data/swconf.js'; |
| 4 | +const params = new URL(location).searchParams; |
| 5 | +const swconfUrl = params.has('baseurl') |
| 6 | + ? `${params.get('baseurl')}${swconfPath}` |
| 7 | + : swconfPath; |
| 8 | + |
| 9 | +importScripts(swconfUrl); |
| 10 | +const purge = swconf.purge; |
| 11 | + |
| 12 | +function verifyHost(url) { |
| 13 | + for (const host of swconf.allowHosts) { |
| 14 | + const regex = RegExp(`^http(s)?://${host}/`); |
| 15 | + if (regex.test(url)) { |
| 16 | + return true; |
| 17 | + } |
| 18 | + } |
| 19 | + return false; |
| 20 | +} |
| 21 | + |
| 22 | +function verifyUrl(url) { |
| 23 | + if (!verifyHost(url)) { |
| 24 | + return false; |
| 25 | + } |
| 26 | + |
| 27 | + const requestPath = new URL(url).pathname; |
| 28 | + |
| 29 | + for (const path of swconf.denyPaths) { |
| 30 | + if (requestPath.startsWith(path)) { |
| 31 | + return false; |
| 32 | + } |
| 33 | + } |
| 34 | + return true; |
| 35 | +} |
| 36 | + |
| 37 | +if (!purge) { |
| 38 | + swconf.allowHosts.push(location.host); |
| 39 | +} |
| 40 | + |
| 41 | +self.addEventListener('install', (event) => { |
| 42 | + if (purge) { |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + event.waitUntil( |
| 47 | + caches.open(swconf.cacheName).then((cache) => { |
| 48 | + return cache.addAll(swconf.resources); |
| 49 | + }) |
| 50 | + ); |
| 51 | +}); |
| 52 | + |
| 53 | +self.addEventListener('activate', (event) => { |
| 54 | + event.waitUntil( |
| 55 | + caches.keys().then((keyList) => { |
| 56 | + return Promise.all( |
| 57 | + keyList.map((key) => { |
| 58 | + if (purge) { |
| 59 | + return caches.delete(key); |
| 60 | + } else { |
| 61 | + if (key !== swconf.cacheName) { |
| 62 | + return caches.delete(key); |
| 63 | + } |
| 64 | + } |
| 65 | + }) |
| 66 | + ); |
| 67 | + }) |
| 68 | + ); |
| 69 | +}); |
| 70 | + |
| 71 | +self.addEventListener('message', (event) => { |
| 72 | + if (event.data === 'SKIP_WAITING') { |
| 73 | + self.skipWaiting(); |
| 74 | + } |
| 75 | +}); |
| 76 | + |
| 77 | +self.addEventListener('fetch', (event) => { |
| 78 | + event.respondWith( |
| 79 | + caches.match(event.request).then((response) => { |
| 80 | + if (response) { |
| 81 | + return response; |
| 82 | + } |
| 83 | + |
| 84 | + return fetch(event.request).then((response) => { |
| 85 | + const url = event.request.url; |
| 86 | + |
| 87 | + if (purge || event.request.method !== 'GET' || !verifyUrl(url)) { |
| 88 | + return response; |
| 89 | + } |
| 90 | + |
| 91 | + // See : <https://developers.google.com/web/fundamentals/primers/service-workers#cache_and_return_requests> |
| 92 | + let responseToCache = response.clone(); |
| 93 | + |
| 94 | + caches.open(swconf.cacheName).then((cache) => { |
| 95 | + cache.put(event.request, responseToCache); |
| 96 | + }); |
| 97 | + return response; |
| 98 | + }); |
| 99 | + }) |
| 100 | + ); |
| 101 | +}); |
0 commit comments