gpt4 book ai didi

javascript - 清除所有内容的 Workbox 缓存

转载 作者:搜寻专家 更新时间:2023-11-01 05:19:18 39 4
gpt4 key购买 nike

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

谷歌搜索并查看 SO,我找到了各种从缓存中清除各种内容的方法。我还没有想出一个简单的方法来“清除所有内容并重新开始”。

我在 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 中)。

谢谢

最佳答案

CacheStorage可在客户端代码(您注册软件的位置)中访问,因此您可以从那里删除它。

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

关于javascript - 清除所有内容的 Workbox 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54376355/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com