Registering a service worker

First, your main script has to register the service worker to the browser. Here's how:

navigator.serviceWorker.register('/sw.js').then(reg => console.log(reg)).catch(err => console.log(err));

The reg object is associated with information about the registration of your service worker.

A service worker registration code can be safely run multiple times. If already registered, the browser will not re-register it.

You can debug service workers here: Chrome-->Inspect-->Service Workers.

Note that a service worker script's scope is the scope where it is located. For example, the preceding file is located in the root directory (localhost/sw.js), so it can intercept all localhost/* requests. If it were located in, say, ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.