Skip to content

Commit

Permalink
fix(service-worker): clear service worker cache in safety worker (#43324
Browse files Browse the repository at this point in the history
)

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
  • Loading branch information
naveedahmed1 authored and AndrewKushnir committed Sep 13, 2021
1 parent baf8145 commit a102b27
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
9 changes: 5 additions & 4 deletions aio/content/guide/service-worker-devops.md
Expand Up @@ -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
Expand All @@ -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

Expand Down
10 changes: 8 additions & 2 deletions packages/service-worker/safety-worker.js
Expand Up @@ -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)));
}));
});

0 comments on commit a102b27

Please sign in to comment.