Course contentsShow
← Web Development
Lesson 2411 of 2,98243. Service Workers Deep DiveFree lesson

Broadcast Updates for Cache Changes

Notifying open tabs when cached content is updated using the BroadcastUpdate plugin.

Broadcast Updates for Cache Changes

You'll learn how to automatically notify all open tabs when your service worker updates cached content, keeping your UI in sync.

The Problem: Stale Content in Open Tabs

When your service worker updates cached resources in the background (like with stale-while-revalidate), the user's currently open tabs continue displaying the old content. They won't see the fresh data until they refresh the page manually—a poor user experience.

How BroadcastUpdate Solves It

Workbox's BroadcastUpdate plugin uses the Broadcast Channel API to send messages between your service worker and all open tabs whenever a cached resource is updated. Think of it like a radio station broadcasting to all receivers tuned to the same frequency.

When the service worker fetches fresh content that differs from what's cached, the plugin broadcasts a message to all listening tabs. Your page JavaScript can listen for these messages and update the UI or prompt the user to reload.

Basic Implementation

import { registerRoute } from 'workbox-routing';
import { StaleWhileRevalidate } from 'workbox-strategies';
import { BroadcastUpdatePlugin } from 'workbox-broadcast-update';

registerRoute(
  ({url}) => url.pathname.startsWith('/api/'),
  new StaleWhileRevalidate({
    plugins: [
      new BroadcastUpdatePlugin()
    ]
  })
);

In your page script:

const updateChannel = new BroadcastChannel('workbox');

updateChannel.addEventListener('message', event => {
  console.log('Cache updated for:', event.data.payload.updatedURL);
  // Show "New content available" banner or auto-refresh
});

The plugin automatically detects meaningful cache updates (not just timestamp changes) and notifies all tabs, allowing you to provide real-time feedback without forcing disruptive reloads.

Key Takeaway: Workbox's BroadcastUpdate plugin keeps all open tabs informed when cached content changes, enabling you to build responsive, real-time user experiences with background cache updates.