workbox-broadcast-cache-update

A helper library that uses the Broadcast Channel API to announce when a caches entry is updated with a new response, allowing your web app to listen for these updates and react to them.

Most developers will use this module by instantiating a new BroadcastCacheUpdatePlugin and passing it to a RequestWrapper, as shown in the first example below.

You can listen for updates from your web app by adding an event listener on a BroadcastChannel within a page, using the same channel name as what's used within the service worker, as shown in the second example.

Examples

Using the BroadcastCacheUpdatePlugin class in a service worker.

const requestWrapper = new workbox.runtimeCaching.RequestWrapper({
  cacheName: 'text-files',
  plugins: [
    new workbox.broadcastCacheUpdate.BroadcastCacheUpdatePlugin(
      {channelName: 'cache-updates'})
  ],
});

const route = new workbox.routing.RegExpRoute({
  regExp: /\.txt$/,
  handler: new workbox.runtimeCaching.StaleWhileRevalidate({requestWrapper}),
});

const router = new workbox.routing.Router();
router.registerRoute({route});

Listening for the broadcast message in the window.

const updateChannel = new BroadcastChannel('cache-updates');
updateChannel.addEventListener('message', event => {
  console.log(`Cache updated: ${event.data.payload.updatedUrl}`);
});

Classes

BroadcastCacheUpdate
BroadcastCacheUpdatePlugin

Member Variables

(static, constant) cacheUpdatedMessageType string

This is a static variable for the cache updated message type. Useful for comparing to the messages type parameter to identify the kind of message.

Example
// Prints 'CACHE_UPDATED'
console.log(workbox.broadcastCacheUpdate.cacheUpdatedMessageType);