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.
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, ...