最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to clear service worker cache programmatically? - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question asked Mar 1, 2018 at 23:56 CocoCoco 1,6305 gold badges25 silver badges45 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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.

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);
    });
  });
}
发布评论

评论列表(0)

  1. 暂无评论