Using Service Workers Immediately After Install to Listen to Fetch Events without Refresh

Chris Washington
2 min readAug 10, 2020

Problem

If at any point in time you wanted to intercept fetch calls within your service worker, you may have noticed that after installing the service worker, that only after a page refresh do you get to take advantage of the interceptor.

This doesn’t create an ideal user (nor developer) experience for some use cases where it is imperative to intercept all calls coming from a web application.

Even when following the patterns for immediate activation within your service worker like so:

You will notice that fetch calls may not always, if ever, begin to be intercepted.

Thankfully there is a way around this perceived hiccup.

Pattern

We can utilize service worker messages to force the activation and as a result properly wait for activation of the service worker before starting the application.

Let’s start with the service worker code. Remember the goal is to be able to intercept the fetch event without needing to do a page refresh:

Take particular note of the message event listener. This particular listener is waiting for an “activate-app” message. At that point it will skipWaiting for any other registrations, claim all clients and then return a message “start-app” stating that it is ready to intercept all fetch events.

In the main part of your application you can then just simply have the following:

By registering the service worker with the browser, when ready the application can listen for the start-app event. Once received, the application can then follow any other logic necessary.

Final Output

I like to simplify things a bit by wrapping this code into a class for easier consumption of the behaviors listed here:

--

--

Chris Washington

Chris is a Sr. Lead Software Engineer at Capital One just doing what he loves: creating epic things, and writing about them.