|
| 1 | +/* |
| 2 | + * Last Modified: 2026-04-08 |
| 3 | + * Resources: |
| 4 | + * - Progressive Web Apps: Going Offline https://developers.google.com/codelabs/pwa-training/pwa03--going-offline |
| 5 | + */ |
| 6 | + |
| 7 | +// return Promise<Response> |
| 8 | +function cleanResponse(response: Response): Promise<Response> { |
| 9 | + const clonedResponse = response.clone(); |
| 10 | + |
| 11 | + // Not all browsers support the Response.body stream, so fall back to reading |
| 12 | + // the entire body into memory as a blob. |
| 13 | + const bodyPromise = clonedResponse.body ? |
| 14 | + Promise.resolve(clonedResponse.body) : |
| 15 | + clonedResponse.blob(); |
| 16 | + |
| 17 | + return bodyPromise.then((body) => { |
| 18 | + // new Response() is happy when passed either a stream or a Blob. |
| 19 | + return new Response(body, { |
| 20 | + headers: clonedResponse.headers, |
| 21 | + status: clonedResponse.status, |
| 22 | + statusText: clonedResponse.statusText, |
| 23 | + }); |
| 24 | + }); |
| 25 | +} |
| 26 | + |
| 27 | +const LAZY_CACHE_RESOURCES: string[] = []; |
| 28 | + |
| 29 | +// precacheResources: string[] |
| 30 | +export function setup(version: string, precacheResources: string[], lazyCacheResources: string[] = []) { |
| 31 | + const cacheName = "cache-v" + version; |
| 32 | + |
| 33 | + LAZY_CACHE_RESOURCES.push(...lazyCacheResources); |
| 34 | + |
| 35 | + self.addEventListener("install", (event: any) => { |
| 36 | + // Cache all resources for current version. |
| 37 | + // Note that {cache: "reload"} is important here, |
| 38 | + // otherwise we may end up with setting old cached resources as new cache. |
| 39 | + // Ref https://stackoverflow.com/a/64880880 |
| 40 | + console.info(`[Service Worker v${version}] Caching resources...`); |
| 41 | + const requests = precacheResources.map((resource) => new Request(resource, {cache: "reload"}) ); |
| 42 | + event.waitUntil( |
| 43 | + caches.open(cacheName) |
| 44 | + .then((cache) => cache.addAll(requests)) |
| 45 | + .then(() => { |
| 46 | + // Note that this time of loading still uses the old cache. |
| 47 | + // So it's better to propmt the user to update the app. |
| 48 | + /* e.g. display a message like: |
| 49 | + New version x.y.z is available. |
| 50 | + To update, close all active tabs of this website and open again. |
| 51 | + (Simply refreshing this page won't take effect.) |
| 52 | + */ |
| 53 | + const channel = new BroadcastChannel("SW_MESSAGES"); |
| 54 | + channel.postMessage({title: "APP_UPDATE", version: version}); |
| 55 | + }) |
| 56 | + ); |
| 57 | + }); |
| 58 | + |
| 59 | + self.addEventListener("activate", (event: any) => { |
| 60 | + console.info(`[Service Worker v${version}] Activated.`); |
| 61 | + |
| 62 | + // Delete old caches |
| 63 | + event.waitUntil( |
| 64 | + caches.keys().then(keyList => { |
| 65 | + return Promise.all( |
| 66 | + keyList.map(key => { |
| 67 | + if (key !== cacheName) { |
| 68 | + console.info(`[Service Worker v${version}] Deleting old cache: ${key}`); |
| 69 | + return caches.delete(key); |
| 70 | + } |
| 71 | + }) |
| 72 | + ); |
| 73 | + }) |
| 74 | + ); |
| 75 | + }); |
| 76 | + |
| 77 | + self.addEventListener("fetch", (event: any) => { |
| 78 | + event.respondWith( |
| 79 | + /* |
| 80 | + Make sure to write `caches.open(cacheName).then(...)` instead of simple `caches.match(event.request)`. |
| 81 | + It may somehow fail to delete old cache so that the user will get stuck in old cache. |
| 82 | + Maybe it's because the tab is closed during the execution of the listener function of "activate" event? |
| 83 | + */ |
| 84 | + caches.open(cacheName).then(async function(cache) { |
| 85 | + const cachedResponse = await cache.match(event.request); |
| 86 | + if (cachedResponse) { |
| 87 | + // A cached response of **/index.html may contain a mark of redirected=true, |
| 88 | + // which will cause browser to block the response due to security concerns. |
| 89 | + // So we need to somehow remove this mark from the response. |
| 90 | + // https://stackoverflow.com/questions/45434470/only-in-chrome-service-worker-a-redirected-response-was-used-for-a-reque |
| 91 | + if (cachedResponse.redirected === true && event.request.url.endsWith("/index.html")) { |
| 92 | + return cleanResponse(cachedResponse); |
| 93 | + } |
| 94 | + return cachedResponse; |
| 95 | + } else { |
| 96 | + const response = await fetch(event.request); |
| 97 | + if (LAZY_CACHE_RESOURCES.includes(event.request.url)) { |
| 98 | + cache.put(event.request.url, response.clone()); |
| 99 | + } |
| 100 | + return response; |
| 101 | + } |
| 102 | + }) |
| 103 | + ); |
| 104 | + }); |
| 105 | +} |
0 commit comments