为一条路线手动执行 workbox.expiration.Plugin.deleteCacheAndMetadata()

Manually execute workbox.expiration.Plugin.deleteCacheAndMetadata() for a route

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

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

我认为要牢记的主要事情是 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();
  }
});