Skip to main content

BroadcastCacheUpdate

First added

Workbox

About

A class that uses the postMessage() API to inform any open windows/tabs when a cached response has been updated.

For efficiency's sake, the underlying response bodies are not compared; only specific response headers are checked.

Options

  • headersToCheck โ€” A list of headers that will be used to determine whether the responses differ.
  • generatePayload(options) โ€” A function whose return value will be used as the payload field in any cache update messages sent to the window clients.
  • notifyAllClients โ€” If true (the default) then all open clients will receive a message. If false, then only the client that make the original request will be notified of the update.

Methods and fields

  • async notifyIfUpdated(options) โ€” Compares two responses and sends a message (via postMessage()) to all window clients if the responses differ. Neither of the responses can be opaque.

Usage

import { BroadcastCacheUpdate, BROADCAST_UPDATE_DEFAULT_HEADERS } from "serwist";

const broadcastUpdate = new BroadcastCacheUpdate({
  headersToCheck: [...BROADCAST_UPDATE_DEFAULT_HEADERS, "X-My-Custom-Header"],
});

const cacheName = "api-cache";
const request = new Request("https://example.com/api");

const cache = await caches.open(cacheName);
const oldResponse = await cache.match(request);
const newResponse = await fetch(request);

broadcastUpdate.notifyIfUpdated({
  cacheName,
  oldResponse,
  newResponse,
  request,
  event,
});