5

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?

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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);
    });
  });
}

1 Comment

In which file add these lines of code?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.