首页 > 解决方案 > 为路由手动执行 workbox.expiration.Plugin.deleteCacheAndMetadata()

问题描述

该方法workbox.expiration.Plugin.deleteCacheAndMetadata()最近已添加到工作箱中。如何为我设置缓存的特定路线触发此功能?

这里的用例是当客户端上发生某些操作时,我需要删除缓存。我可以直接从客户端删除缓存,但这会留下元数据(在 indexedDB 中)。所以我宁愿向服务人员发送消息并使用工作箱方法进行清理。如何获得正确的过期插件实例来调用该方法?

标签: workbox

解决方案


我认为要记住的主要事情是workbox.expiration.Plugin实例与路由无关——它被传递给给定的策略。它可以存在于路由定义之外,您可以稍后在代码中引用它。

这是一个例子:

const expirationPlugin = new workbox.expiration.Plugin({
  maxEntries: 20,
}),

workbox.routing.registerRoute(
  new RegExp('/images/'),
  workbox.strategies.cacheFirst({
    cacheName: 'image-cache',
    plugins: [
      expirationPlugin,
    ],
  })
);

self.addEventListener('message', (event) => {
  if (event.data === 'clear-cache') {
    expirationPlugin.deleteCacheAndMetadata();
  }
});

推荐阅读