Intercept Http Request Using Serviceworker

Maulanamaleek
2 min readOct 18, 2021

--

In this article, we will discuss about how to intercept Http request and respond with custom responses using serviceworker.

Http request is a request that happen on top of a web application to request resources like image, javascript, css, links, etc, from an html page.

When intercepting request, we can add a fetch listener to filter requests and give a custom responses if we want to. It will allow us to give a response of blob file, instead of a real file.

If we meet a condition when we don’t have the filetype data, but we want to response an object / any type as related filetype, we can do it with http interception.

Preparation

Before we continue, we want to check that our browsers are supported by serviceworker, here. Currently, only IE and IOS Webview that aren’t support serviceworker yet.

Register the serviceworker

create sw.js near our index.html :

self.addEventListener('fetch', function(event) {
const url = event.request.url;
if (url.endsWith('style.css'){
event.respondWith('your_file_response')
}
})

register sw.js inside index.html :

if (“serviceworker” in navigator) {
navigator.serviceWorker.register('sw.js').then(function(reg){
if (reg.active) console.log('serviceworker installed')
})
.catch(function(err){
console.log('registration failed: ' + err)
})
}

Now, we have already installed the servicewoker.

Custom Response

To create a custom response from blob file, we can do something like this:

const myFile = "...." //text-based data(perhaps html,css, js, etc)const blob = new Blob([myFile], { type: "text/css" })const myresponse = new Response(blob, { headers: { contentType: "text/css" }) // the custom responseself.addEventListener('fetch', function(event) {
const url = event.request.url;
if (url.endsWith('style.css'){
event.respondWith(myresponse) // add your custom response
}
})

In the example above, I want to respond a custom stylesheet from a text variable in javascript. Of course, you can do the same approach with html, js, and image format.

# Communicate with Serviceworker

We don’t want to store our data inside sw.js , so we need a communication method to transfer data from our javascript functions to the serviceworker.

I recommend to use .postMessage api to send any data to any target, read more here.

In our javascript file, use this code:

const data = [] //any data you want to transfer// let's transfer it to the serviceworker
if (navigator.serviceWorker.controller){
navigator.serviceWorker.postMessage(data)
}

We also need to provide message listener inside service worker sw.js:

let data;self.addEventListener('message', function(event) {
data = event.data
})

now, we are finished to setup the communication method. You can always use this example for any kind of interception with custom respond

--

--