How to clear cache of service worker?
Solution 1:
If you know the cache name you can simply call caches.delete()
from anywhere you like in the worker:
caches.delete(/*name*/);
And if you wanted to wipe all caches (and not wait for them, say this is a background task) you only need to add this:
caches.keys().then(function(names) {
for (let name of names)
caches.delete(name);
});
Solution 2:
Use this to delete outdated caches:
self.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.filter(function(cacheName) {
// Return true if you want to remove this cache,
// but remember that caches are shared across
// the whole origin
}).map(function(cacheName) {
return caches.delete(cacheName);
})
);
})
);
});
Solution 3:
Typically you update the CACHE_NAME
in your service workers JS file so your worker installs again:
self.addEventListener('install', evt => {
evt.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(inputs))
)
})
Alternatively, to clear the cache for a PWA find the cache name:
self.caches.keys().then(keys => { keys.forEach(key => console.log(key)) })
then run the following to delete it:
self.caches.delete('my-site-cache')
Then refresh the page.
If you see any worker-related errors in the console after refreshing, you may also need to unregister the registered workers:
navigator.serviceWorker.getRegistrations()
.then(registrations => {
registrations.forEach(registration => {
registration.unregister()
})
})