From 45e71af01e5ce8afe8b03ac59215d1c2408191f1 Mon Sep 17 00:00:00 2001 From: Tusooa Zhu Date: Tue, 11 Jan 2022 23:03:46 -0500 Subject: [PATCH] Fix the bug where remote media fail to load without media proxy --- src/sw.js | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/sw.js b/src/sw.js index c8baad55..391f3a5d 100644 --- a/src/sw.js +++ b/src/sw.js @@ -107,8 +107,12 @@ self.addEventListener('notificationclick', (event) => { })) }) -self.addEventListener('fetch', async (event) => { - if (shouldCache) { +self.addEventListener('fetch', (event) => { + console.log(`[Service Worker] Got: ${event.request.url}`) + console.debug(event.request) + // Do not mess up with remote things + const isSameOrigin = (new URL(event.request.url)).origin === self.location.origin + if (shouldCache && event.request.method === 'GET' && isSameOrigin) { event.respondWith((async () => { const r = await caches.match(event.request) console.log(`[Service Worker] Fetching resource: ${event.request.url}`) @@ -116,13 +120,18 @@ self.addEventListener('fetch', async (event) => { return r } - const response = await fetch(event.request) - if (response.ok && isEmoji(event.request)) { - console.log(`[Service Worker] Caching emoji ${event.request.url}`) - const cache = await caches.open(emojiCacheKey) - await cache.put(event.request.clone(), response.clone()) + try { + const response = await fetch(event.request) + if (response.ok && isEmoji(event.request)) { + console.log(`[Service Worker] Caching emoji ${event.request.url}`) + const cache = await caches.open(emojiCacheKey) + await cache.put(event.request.clone(), response.clone()) + } + return response + } catch (e) { + console.log('error:', e) + throw e } - return response })()) } })