Reputation: 439
I have been working on pwa project and i opened two cache one is static-cache and another one is dynamic-cache i am able to delete one cache at a time by using this code
self.addEventListener('activate', event => {
console.log('Activating new service worker...');
const cacheWhitelist = [staticCacheName];
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
i want to delete both caches at same time
Upvotes: 0
Views: 785
Reputation: 10870
Your code looks already good. In my case, I use the following code to delete the SW caches:
if ('caches' in window) {
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.filter(cacheName => {
// You can have some custom logic here, if you want
// to delete only some caches
// If you return TRUE, the cache will be deleted
}).map(cacheName => {
return caches.delete(cacheName);
})
);
})
}
The caches.keys()
method returns the keys of the CacheStorage, an interface representing the storage for the Cache objects that can be accessed by the service worker.
I wrote an article about service workers and caching strategies, if you want to deepen the topic.
Upvotes: 3
Reputation: 3893
try this:
self.addEventListener( "activate", event => {
event.waitUntil(
//wholesale purge of previous version caches
caches.keys().then( cacheNames => {
cacheNames.forEach( value => {
caches.delete( value );
} );
} );
} );
Upvotes: 1
Reputation: 749
Not an expert but I think using filter like this will work.
cacheNames.filter(cacheName => {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
Upvotes: 1