Javascript 如何清除服务工作者的缓存?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45467842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:04:02  来源:igfitidea点击:

How to clear cache of service worker?

javascripthtmlgoogle-chromeservice-worker

提问by taek

So, I have an HTML page with service worker, the service worker cache the index.html and my JS files.

所以,我有一个带有服务工作者的 HTML 页面,服务工作者缓存 index.html 和我的 JS 文件。

The problem is when I change the JS, the change doesn't show up directly on the client browser. Of course in chrome dev-tools, I can disable cache. But in chrome mobile, how do I do that?

问题是当我更改 JS 时,更改不会直接显示在客户端浏览器上。当然,在 chrome dev-tools 中,我可以禁用缓存。但是在 chrome mobile 中,我该怎么做?

I tried to access the site settings and hit the CLEAR % RESET button. But it still loads the old page/load from cache. I tried to use other browser or chrome incognito and it loads the new page.

我尝试访问站点设置并点击 CLEAR % RESET 按钮。但它仍然从缓存加载旧页面/加载。我尝试使用其他浏览器或 chrome incognito 并加载新页面。

Then, I try to clear my browsing data (just cache) and it works.

然后,我尝试清除我的浏览数据(只是缓存)并且它有效。

I guess that's not how it should work right? my user won't know if the page is updated without clearing the chrome browser cache.

我想这不是它应该如何工作的吗?我的用户不会知道页面是否在不清除 chrome 浏览器缓存的情况下更新。

采纳答案by elf

Use this to delete outdated caches:

使用它来删除过时的缓存:

self.addEventListener('activate', function(event) {
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.filter(function(cacheName) {
          // Return true if you want to remove this cache,
          // but remember that caches are shared across
          // the whole origin
        }).map(function(cacheName) {
          return caches.delete(cacheName);
        })
      );
    })
  );
});

回答by Hashbrown

If you know the cache name you can simply call caches.delete()from anywhere you like in the worker:

如果您知道缓存名称,您可以简单地caches.delete()从工作程序中您喜欢的任何地方调用:

caches.delete(/*name*/);

And if you wanted to wipe all caches (and not wait for them, say this is a background task) you only need to add this:

如果您想擦除所有缓存(而不是等待它们,假设这是一项后台任务),您只需要添加以下内容

caches.keys().then(function(names) {
    for (let name of names)
        caches.delete(name);
});

回答by Josh Habdas

Typically you update the CACHE_NAMEin your service workers JS file so your worker installs again:

通常,您会更新CACHE_NAMEService Workers JS 文件中的 ,以便您的工作人员再次安装:

self.addEventListener('install', evt => {
  evt.waitUntil(
    caches.open(CACHE_NAME).then(cache => cache.addAll(inputs))
  )
})

Alternatively, to clearthe cache for a PWA:

或者,要清除PWA 的缓存:

self.caches.keys().then(keys => { keys.forEach(key => console.log(key)) })

to list the names of the cache keys, then run:

列出缓存键的名称,然后运行:

self.caches.delete('my-site-cache')

to delete a cache key by name (i.e., my-site-cache). Then refresh the page.

按名称删除缓存键(即 my-site-cache)。然后刷新页面。

If you see any worker-related errors in the console after refreshing, you may also need to unregister the registered workers:

如果刷新后在控制台中看到任何与 worker 相关的错误,您可能还需要取消注册已注册的 worker:

navigator.serviceWorker.getRegistrations()
  .then(registrations => {
    registrations.forEach(registration => {
      registration.unregister()
    }) 
  })

回答by Shadi Namrouti

This is the only code that worked for me. It is my adaptation of Mozilla documentation:

这是唯一对我有用的代码。这是我对Mozilla 文档的改编:

//Delete all caches and keep only one
const cachNameToKeep = 'myCache';

//Deletion should only occur at the activate event
self.addEventListener('activate', event => {
    var cacheKeeplist = [cacheName];
    event.waitUntil(
        caches.keys().then( keyList => {
            return Promise.all(keyList.map( key => {
                if (cacheKeeplist.indexOf(key) === -1) {
                    return caches.delete(key);
                }
            }));
        })
.then(self.clients.claim())); //this line is important in some contexts
});