清除所有内容的Workbox缓存

时间:2019-01-26 07:00:28

标签: javascript workbox

在javascript网络应用程序的Service Worker中使用Workbox。 想要清除所有内容的整个工作箱/应用程序缓存...基本上返回到与将应用程序首次加载到浏览器之前的状态尽可能相似的状态,然后可能通过window.location.href刷新='/'。

在Google上进行搜索和查找后,我发现了用于清除缓存中各种内容的各种方法。我无法找出一种简单的方法来“清除所有内容并重新开始”。

我在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();
    }
});

在客户端与此配对:

navigator.serviceWorker.controller.postMessage("clearCache");

这显然无效,尽管消息显然已经通过。另外,这似乎是一个不太好的解决方案,我认为有一个更简单的解决方案。

这怎么办?

如何在浏览器的客户端js中从客户端启动它?这在服务器端代码(例如sw.js)中有什么要求。

谢谢

2 个答案:

答案 0 :(得分:4)

CacheStorage可通过客户端代码(在其中注册软件)进行访问,因此可以从此处删除它。

caches.keys().then(cacheNames => {
  cacheNames.forEach(cacheName => {
    caches.delete(cacheName);
  });
});

答案 1 :(得分:3)

如果我们只删除缓存,那么它会损坏 Service Worker,Service Worker 将无法正常工作,因此我们必须取消注册 Service Worker,然后必须删除缓存,然后 重新注册 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)
    }