From a102b27641e3ad00401dd6d2635b9ddcf1151251 Mon Sep 17 00:00:00 2001 From: Naveed Ahmed Date: Mon, 13 Sep 2021 19:59:06 +0300 Subject: [PATCH] fix(service-worker): clear service worker cache in safety worker (#43324) clear angular service worker cache in safety worker to ensure stale or broken contents are not served in future requests Fixes #43163 PR Close #43324 --- aio/content/guide/service-worker-devops.md | 9 +++++---- packages/service-worker/safety-worker.js | 10 ++++++++-- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/aio/content/guide/service-worker-devops.md b/aio/content/guide/service-worker-devops.md index d9f5d73968f56..3eabc28fae4c9 100644 --- a/aio/content/guide/service-worker-devops.md +++ b/aio/content/guide/service-worker-devops.md @@ -326,8 +326,9 @@ essentially self-destructing. Also included in the `@angular/service-worker` NPM package is a small script `safety-worker.js`, which when loaded will unregister itself -from the browser. This script can be used as a last resort to get rid -of unwanted service workers already installed on client pages. +from the browser and remove the service worker caches. This script can +be used as a last resort to get rid of unwanted service workers already +installed on client pages. It's important to note that you cannot register this worker directly, as old clients with cached state may not see a new `index.html` which @@ -339,8 +340,8 @@ most sites, this means that you should serve the safety worker at the old Service Worker URL forever. This script can be used both to deactivate `@angular/service-worker` -as well as any other Service Workers which might have been served in -the past on your site. +(and remove the corresponding caches) as well as any other Service +Workers which might have been served in the past on your site. ### Changing your app's location diff --git a/packages/service-worker/safety-worker.js b/packages/service-worker/safety-worker.js index e960603093719..d98014b5f69c7 100644 --- a/packages/service-worker/safety-worker.js +++ b/packages/service-worker/safety-worker.js @@ -14,7 +14,13 @@ self.addEventListener('install', event => { self.addEventListener('activate', event => { event.waitUntil(self.clients.claim()); - self.registration.unregister().then(() => { + + event.waitUntil(self.registration.unregister().then(() => { console.log('NGSW Safety Worker - unregistered old service worker'); - }); + })); + + event.waitUntil(caches.keys().then(cacheNames => { + const ngswCacheNames = cacheNames.filter(name => /^ngsw:/.test(name)); + return Promise.all(ngswCacheNames.map(name => caches.delete(name))); + })); });