15

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

1

2 Answers 2

43
+50

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);
  });
});
5
  • 4
    FANTASTIC. Super helpful. Worked like a charm. Super simple. This is the magic of SO. No idea how much trouble you just saved me (and I hope a lot of other people too). Thanks very much. Jan 31, 2019 at 3:18
  • What about the precache? The above can be used to empty the cache, but workbox has this indexedDB database too. I tried deleting that too, but when I reload the app, workbox doesn't repopulate it or the precache. Oct 26, 2020 at 5:34
  • Are you using Workbox 5 @MaxWaterman? That uses caches and not IndexedDB.
    – simbolo
    Dec 29, 2020 at 12:43
  • @simbolo looks like I'm using 3.6.3...yeah, I know...but I have actual features to implement so the times I get to upgrade things like workbox is quite minimal....company is being hammered quite hard by covid, and work load is up and #developers/testers down... Are you saying that I should upgrade in order to avoid this problem? I mean, there is a precache cache, but the contents of it are 'managed' using an indexeddb...well, that's what it seems like to me. Devtools manages to 'clear' everything necessary to start from scratch...I just want to do the same from my app. Dec 30, 2020 at 13:07
  • 1
    carefull with this... it can delete the new precache after reload...
    – Ray Foss
    Apr 22, 2021 at 14:11
4

If we only delete the cache then it damage service worker ,service worker will not work properly, so we have to unregister service worker then have to delete cache and then reregister service worker.

refreshCacheAndReload = () => {
        if ('serviceWorker' in navigator) {
          serviceWorkerRegistration.unregister();
          caches.keys().then(cacheNames => {
            cacheNames.forEach(cacheName => {
              caches.delete(cacheName);
            });
          }).then(() => {
            serviceWorkerRegistration.register();
          })
        }
        setTimeout(function () { window.location.replace(""); }, 300)
    }
4
  • Thanks for taking the time to provide an answer to the question. Code-only answers are discouraged on SO. Please consider adding some additional explanation about why your answer solves the problem.
    – DaveL17
    Apr 8, 2021 at 16:19
  • if we only delete the cache then it damage service worker , service worker will not work properly , so we have to unregister service worker then have to delete cache and then re register service woker. Thanks Apr 27, 2021 at 6:11
  • this all about HTTP request cache scenario thank for detailed article -:Jeff Posnick. you can read more about this post, web.dev/runtime-caching-with-workbox
    – vinny
    Apr 27, 2021 at 6:31
  • @DhavalPatel Thank you for taking the time to update your answer. It's preferred to add new information to the answer itself using the Edit button above, rather than in comments. Readers of your answer may not take the time to read the comments section.
    – DaveL17
    Apr 27, 2021 at 11:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.