Service Worker Introduction

Step-by-step introduction to the Service Worker API.

Hijack fetch

The service worker can intercept requests and manipulate them. You can also modify the responses or craft new ones, using event.respondWith.

Code

// in sw.js
this.addEventListener('fetch', event => {
  event.respondWith(new Response('hijacked'));
});

The Response constructor accepts additional option, like setting {'Content-Type':'text/html'} headers.

Output