From e84331b26ae05281b801c328c9fb257087ca64b8 Mon Sep 17 00:00:00 2001 From: Cotes Chung <11371340+cotes2020@users.noreply.github.com> Date: Tue, 13 Apr 2021 13:18:43 +0800 Subject: [PATCH] Fix the response stream of service worker After service worker update (rebuild the site), the following error will occasionally appear: ``` The FetchEvent for "" resulted in a network error response: an "opaque" response was used for a request whose type is not no-cors ``` This commit ensures that the response object has been cached before being returned. --- sw.js | 47 +++++++++++++++++++++++++++++------------------ 1 file changed, 29 insertions(+), 18 deletions(-) diff --git a/sw.js b/sw.js index 563302a..c8074db 100644 --- a/sw.js +++ b/sw.js @@ -36,28 +36,39 @@ self.addEventListener('install', e => { ); }); -self.addEventListener('fetch', e => { - e.respondWith( - caches.match(e.request).then(r => { - /* console.log(`[sw] method: ${e.request.method}, fetching: ${e.request.url}`); */ - return r || fetch(e.request).then(response => { - const url = e.request.url; - - if (e.request.method !== 'GET' - || !verifyDomain(url) - || isExcluded(url)) { +self.addEventListener('fetch', event => { + event.respondWith( + caches.match(event.request) + .then(response => { + if (response) { return response; } - return caches.open(cacheName).then(cache => { - /* console.log('[sw] Caching new resource: ' + e.request.url); */ - cache.put(e.request, response.clone()); - return response; - }); + return fetch(event.request) + .then(response => { + const url = event.request.url; - }); - }) - ); + if (event.request.method !== 'GET' || + !verifyDomain(url) || + isExcluded(url)) { + return response; + } + + /* + see: + */ + let responseToCache = response.clone(); + + caches.open(cacheName) + .then(cache => { + /* console.log('[sw] Caching new resource: ' + event.request.url); */ + cache.put(event.request, responseToCache); + }); + + return response; + }); + }) + ); }); self.addEventListener('activate', e => {