detecting service worker support

2021-02-11

 | 

~3 min read

 | 

426 words

The app I’m working on uses Service Workers extensively. To make sure users get the experience we expect, we’ve added a detection step within our code to display a banner if service workers aren’t available.

if (!("serviceWorker" in navigator)) {
  throw new Error("Service Workers not supported")
}
//...

I wanted to test if this check actually worked, which meant I needed:

  1. to figure out how to block Service Workers, or
  2. use a browser that didn’t support Service Workers.

I pursued the blocking Service Workers first and discovered:

  1. Chrome does not allow you to block service workers exclusively.

    You can deregister servicer workers1 once they’ve started, but in order to prevent all service workers, you need to block cookies. This can be done via the internal URL: chrome://settings/cookies. Of course, this can affect other parts of the application beyond just the purview of the service workers.

  2. While Service Workers are Javascript, blocking Javascript on the site did not seem to prevent the registration and running of service workers (this was the biggest surprise of the whole process).

    To block Javascript within Chrome, open Dev Tools, open the Command Palette (⌘+⇧+p), and search for Disable Javascript.

Of course, it’s only after the fact that I realized even if these approaches worked, they wouldn’t have tripped my code because serviceWorkers would still have been on the navigator instance!

Phase two: Old browsers!

Service workers have been around for a few years! You have to go all the way back to Chrome 43 (April 2015) or Safari 11 (September 2017) in order to not have support.

I don’t have those browsers readily available, but fortunately, we have a license with Sauce Labs which does!

Once I booted up an old version, I was able to easily confirm that the browser didn’t support Service Workers as the error was thrown just as expected!

Wrap Up

While I learned a lot in the process, this was, more than anything, a good reminder to ask why. I tried everything other than using an old browser first because I thought I could be clever. In retrospect, however, I realized that even if I had successfully blocked the Service Worker, I wouldn’t have actually tripped my detection method!

Ah well. I got there in the end and I learned along the way.

Footnotes

  • 1 To deregister service workers for a specific site, you can find them in the Dev Tools. Navigate to Application > Service Workers. You can find all registered service workers at chrome://serviceworker-internals/

Related Posts
  • 2021 Daily Journal


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!