Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting when Workbox precaching has completed

I need to have an event or plugin to know that precache process is successfully finished inside of the service worker.

I know how accomplish it natively

self.serviceWorker.addEventListener('statechange', function() {
   if (this.state === 'installed') {
     ...
   }
});

but how to with workbox?

like image 318
Vadim Avatar asked Oct 14 '25 08:10

Vadim


1 Answers

Workbox precaching also takes place during the install event, so you could listen for a similar state change.

Additionally, if you want more fine-grained reporting, you could use a Workbox plugin inside of your service worker that then called postMessage() to open clients reporting back the status (either when everything is complete, or after each response is cached):

import {addPlugins, precacheAndRoute} from '../../packages/workbox-precaching';

const manifest = self.__WB_MANIFEST || [];
const manifestSize = manifest.length;
let precacheCount = 0;

async function sendToClients(message) {
  const clients = await self.Clients.matchAll();
  for (const client of clients) {
    client.postMessage(message);
  }
}

const handlerDidComplete = async ({request, error, event}) => {
  if (event.type === 'install') {
    if (error) {
      sendToClients(`Error while precaching ${request.url}: ${error}`);
    } else {
      precacheCount++;
      if (precacheCount >= manifestSize) {
        sendToClients(`Finished precaching ${manifestSize} entries.`);
      }
    }
  }
};

addPlugins([{handlerDidComplete}]);
precacheAndRoute(manifest);

You'd then listen for these messages in your client pages using navigator.serviceWorker.addEventListener('message', () => {...}).

Again, this is optional, as you can just rely on the built-in APIs for listening to service worker lifecycle changes, even when you're using Workbox.

like image 115
Jeff Posnick Avatar answered Oct 17 '25 05:10

Jeff Posnick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!