Coco
Coco

Reputation: 1630

How to clear service worker cache programmatically?

I have a site with a service worker with multiple caches, which have files used for different reasons. I'd to be able to clear (or delete) one particular cache from my program on demand, not from within the service worker itself. This is what I've tried:

async function clearCache(cacheName) {
  if ('caches' in window) {
    return await caches.delete(cacheName);
  } 
}

I can get the cache from the window object, but can't seem to delete it. I've also tried looping through the cache and deleting all the files individually, but that didn't work either.

Is this possible?

Upvotes: 5

Views: 4155

Answers (2)

Suhail Taj
Suhail Taj

Reputation: 1074

This worked for me for cleaning everything from cache programmatically.

if ('serviceWorker' in navigator) {
  caches.keys().then(function(cacheNames) {
    cacheNames.forEach(function(cacheName) {
      caches.delete(cacheName);
    });
  });
}

Upvotes: 2

Jeff Posnick
Jeff Posnick

Reputation: 56154

Yes, that code should delete the cache. (You could simplify it a little bit by omitting the async/await, since the code was already returning a promise, but that doesn't really matter.)

If you're not seeing the cache disappear right away, then it's possible that there's a different variable in scope which is maintaining a reference to an open instance of the cache. As per the specification:

Note: After this step, the existing DOM objects (i.e. the currently referenced Cache, Request, and Response objects) should remain functional.

In practice, that means that if you have an open instance of cacheName in scope somewhere, the deletion won't take place until after it's closed or falls out of scope.

Upvotes: 4

Related Questions