Clear Workbox cache of all content

好久不见. 提交于 2019-12-07 08:34:01

问题


Using Workbox in a service worker in a javascript webapp. Want to clear the entire workbox/application cache of all content... basically go back to a state as similar as possible to the state before first load of the app into a browser, potentially to be followed by refreshing via window.location.href = '/'.

Googling and looking on SO, I have found various recipes for clearing various things from the cache. I have not been able to figure out a simple way to just 'clear everything and start over'.

I tried this in server code in 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();
    }
});

paired with this on the client:

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

This didn't work, though the message was apparently passed. Also, this seems an inelegant solution and I presume there is a simpler one.

How can this be done?

How can it be initiated from the client side in client side js on the browser? What does this require in server side code (eg in sw.js).

Thank you


回答1:


CacheStorage is accessible in the client code (where you register the SW) so you can delete it from there.

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


来源:https://stackoverflow.com/questions/54376355/clear-workbox-cache-of-all-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!