Advanced Recipes

Offer a page reload for users

A common UX pattern for progressive web apps is to show a banner when a service worker has updated and waiting to install.

To do this you'll need to add some code to your page and to your service worker.

Add to your page

function showRefreshUI(registration) {
  // TODO: Display a toast or refresh UI.

  // This demo creates and injects a button.

  var button = document.createElement('button'); = 'absolute'; = '24px'; = '24px';
  button.textContent = 'This site has updated. Please click here to see changes.';

  button.addEventListener('click', function() {
    if (!registration.waiting) {
      // Just to ensure registration.waiting is available before
      // calling postMessage()

    button.disabled = true;



function onNewServiceWorker(registration, callback) {
  if (registration.waiting) {
    // SW is waiting to activate. Can occur if multiple clients open and
    // one of the clients is refreshed.
    return callback();

  function listenInstalledStateChange() {
    registration.installing.addEventListener('statechange', function(event) {
      if ( === 'installed') {
        // A new service worker is available, inform the user

  if (registration.installing) {
    return listenInstalledStateChange();

  // We are currently controlled so a new SW may be found...
  // Add a listener in case a new SW is found,
  registration.addEventListener('updatefound', listenInstalledStateChange);

window.addEventListener('load', function() {
  .then(function (registration) {
      // Track updates to the Service Worker.
    if (!navigator.serviceWorker.controller) {
      // The window client isn't currently controlled so it's a new service
      // worker that will activate immediately

    // When the user asks to refresh the UI, we'll need to reload the window
    var preventDevToolsReloadLoop;
    navigator.serviceWorker.addEventListener('controllerchange', function(event) {
      // Ensure refresh is only called once.
      // This works around a bug in "force update on reload".
      if (preventDevToolsReloadLoop) return;
      preventDevToolsReloadLoop = true;
      console.log('Controller loaded');

    onNewServiceWorker(registration, function() {

This code handles the various possible lifecycles of the service worker and detects when a new service worker has become installed and is waiting to activate.

When a waiting service worker is found we set up a 'controllerchange' listener on navigator.serviceWorker so we know when to reload the window. When the user clicks on the UI to refresh the page, we post a message to the new service worker telling it to skipWaiting meaning it'll start to activate.

Add to your service worker

self.addEventListener('message', (event) => {
  if (!{

  switch ( {
    case 'skipWaiting':
      // NOOP

This will receive a the 'skipWaiting' message and call skipWaiting()forcing the service worker to activate immediately.

"Warm" the runtime cache

After configuring some routes to manage caching of assets, you may want to add some files to the cache during the service worker installation.

To do this you'll need to install your desired assets to the runtime cache.

self.addEventListener('install', (event) => {
  const urls = [/* ... */];
  const cacheName = workbox.core.cacheNames.runtime;
  event.waitUntil( => cache.addAll(urls)));

If you setup routes with a custom cachename you can do the same, just replace the cacheName with your custom value.

Provide a fallback response to a route

There are scenarios where returning a fallback response is better than failing to return a response at all. An example is returning a placeholder image when the original image can't be retrieved.

To do this in Workbox you can use the handle() method on strategy to make a custom handler function. Note: You'll need to cache any assets you use for your fallback, in the example below we'd need to cache the FALLBACK_IMAGE_URL.

const FALLBACK_IMAGE_URL = '/images/fallback.png';
const imagesHandler = workbox.strategies.cacheFirst();
worbox.routing.registerRoute(new RegExp('/images/'), ({event}) => {
  return imagesHandler.handle({event})
    .catch(() => caches.match(FALLBACK_IMAGE_URL));

Use postMessage() to notify of cache updates

On browsers which lack Broadcast Channel API support, the workbox-broadcast-cache-update plugin will not send any messages letting clients know that a cached response was updated.

As an alternative to using workbox-broadcast-cache-update, you can instead "roll your own" plugin which listens for the same cache update events, and uses the more widely supported postMessage() API for sending out updates. In this custom plugin, you have control over what criteria are used to determine whether a cached response has been updated. You can use whatever message format inside of postMessage() that makes sense for your use case.

Here's an example of one possible implementation:

const postMessagePlugin = {
  cacheDidUpdate: async ({cacheName, url, oldResponse, newResponse}) => {
    // Use whatever logic you want to determine whether the responses differ.
    if (oldResponse && (oldResponse.headers.get('etag') !== newResponse.headers.get('etag'))) {
      const clients = await self.clients.matchAll();
      for (const client of clients) {
        // Use whatever message body makes the most sense.
        // Note that `Response` objects can't be serialized.
        client.postMessage({url, cacheName});

// Later, use the plugin when creating a response strategy:
  new RegExp('/path/prefix'),
    plugins: [postMessagePlugin],