The question is published on by Tutorial Guruji team.
Using Workbox in a service worker in a javascript webapp. Want to clear the entire workbox/application cache of all content… basically go back to a state as similar as possible to the state before first load of the app into a browser, potentially to be followed by refreshing via window.location.href = ‘/’.
Googling and looking on SO, I have found various recipes for clearing various things from the cache. I have not been able to figure out a simple way to just ‘clear everything and start over’.
I tried this in server code in sw.js:
var logit = true; if (logit) console.log('Service Worker Starting Up for Caching... Hello from sw.js'); importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.6.1/workbox-sw.js'); if (workbox) { if (logit) console.log(`Yay! Workbox is loaded 🎉`); } else { if (logit) console.log(`Boo! Workbox didn't load 😬`); } workbox.routing.registerRoute( // Cache image files /.*.(?:mp3|flac|png|gif|jpg|jpeg|svg|mp4)/, // Use the cache if it's available workbox.strategies.cacheFirst({ // Use a custom cache name cacheName: 'asset-cache', plugins: [ new workbox.expiration.Plugin({ // Cache only 20 images maxEntries: 20, // Cache for a maximum of x days maxAgeSeconds: 3 * 24 * 60 * 60, }) ], }) ); self.addEventListener('message', function(event){ msg = event.data; console.log("SW Received Message: " + msg); if (msg==='clearCache') { console.log('Clearing Workbox Cache.'); WorkBoxCache = new workbox.expiration.Plugin; WorkBoxCache.expirationPlugin.deleteCacheAndMetadata(); //WorkBoxCacheServer.clear(); } });
paired with this on the client:
navigator.serviceWorker.controller.postMessage("clearCache");
This didn’t work, though the message was apparently passed. Also, this seems an inelegant solution and I presume there is a simpler one.
How can this be done?
How can it be initiated from the client side in client side js on the browser? What does this require in server side code (eg in sw.js).
Thank you
Answer
CacheStorage
is accessible in the client code (where you register the SW) so you can delete it from there.
caches.keys().then(cacheNames => { cacheNames.forEach(cacheName => { caches.delete(cacheName); }); });