Search code examples
workbox

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


The method workbox.expiration.Plugin.deleteCacheAndMetadata() has recently been added to workbox. How can I trigger this for a particular route I have setup to cache?

The use case here is that I need to delete a cache when certain actions on the client happen. I could just delete the cache right from the client, but that would leave the metadata (in indexedDB). So I'd rather want to send a message to the service worker and use the workbox method to do the cleanup. How can I get a hand of the correct expiration plugin instance to call the method?


Solution

  • I think the main thing to keep in mind is that the workbox.expiration.Plugin instance is not associated with a route—it's passed in to a given strategy. It can live outside of a route definition, and you can reference it later on in your code.

    Here's an example:

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