Bypass service worker on localhost

Categories

The main thing that’s been holding me back from using Firefox full-time is that there appears to be no way to bypass a service worker. I often use the provided “bypass service worker” option in Chrome dev tools to do this.

I’ve been hunting around and pleading with the web to no avail, so I put the responsibility onto myself.

For now, I just want to ignore localhost urls, but the below snippet could allow you to prevent the service worker’s fetch event from continuing for any hostname that you assign in ignoredHosts.

Code language
javascript
self.addEventListener('fetch', evt => {
  // Define the hostnames that you want to ignore
  const ignoredHosts = ['localhost'];

  // Destructure the hostname out of the event's request
  // URL by creating a new URL instance
  const {hostname} = new URL(evt.request.url);

  // Bail out if our definition contains this url
  if (ignoredHosts.indexOf(hostname) >= 0) {
    return;
  }
});

Go ahead and grab the code from this Gist.

Let’s break it down permalink

  1. You define your host in the ignoredHosts array
  2. We construct a new URL because we can’t access the window in a service worker. This URL gives us access to the magic hostname property which we grab using destructuring to create the hostname constant.
  3. We check the index of the hostname within ignoredHosts. If it’s greater than or equal to 0, we have a match
  4. If it’s a match, we bail out

Wrapping up permalink

A short and sweet tip which I hope you find useful. I can finally use Firefox full-time now which brings me a lot of joy.

If you can improve the above code, hit me up. It’s only a quick fix, so any improvements will be welcomed!

Hello, I’m Andy and I’ll help you to level up your front-end development skills.

I'm a designer and front-end developer who has worked in the design and web industries for over 15 years, and in that time, I have worked with some of the largest organisations in the world, like Google, Harley-Davidson, BSkyB, Unilever, The Natural History Museum, Oracle, Capita, Vice Media and the NHS.

On Piccalilli, I share my knowledge and experience to make you a better front-end developer.

I'm the founder of Set Studio, a creative agency that specialises in building stunning websites that work for everyone. Check out what we're all about.