Search⌘ K
AI Features

Listening to Fetch Events

Explore how to register and handle fetch events in service workers to intercept network requests. Understand how to respond dynamically using the respondWith method, enabling offline support and custom routing in your progressive web application.

Every time the browsers try to fetch any resources (like images, style sheets, scripts, etc.) by sending requests to the network, the fetch event of the service worker gets triggered. To listen to these fetch events of service workers, we need to register a fetch event handler, which triggers the Add-to-Home-screen feature.

Registering the fetch event handler

We can register the fetch event handler as the callback to the addEventListener method provided by the self object of the service worker.

Javascript (babel-node)
// listen to install and active events
// listen to fetch event
self.addEventListener('fetch', function (event){
console.log("Fetch event: ", event);
});

In the above code, we added an event listener for fetch ...