Understanding Service Worker scope

Leave the service worker file in whatever directory imposed by your project structure and set the scope option to / and add the Service-Worker-Allowed HTTP header to the response of your service worker file.

I'm using IIS, so I would add the following to web.config file:

<location path="static/mod/practice/service-worker.js">
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Service-Worker-Allowed" value="/" />
            </customHeaders>
        </httpProtocol>
    </system.webServer>
</location>

And register the worker by:

navigator.serviceWorker.register('/static/mod/practice/service-worker.js', { scope: '/' })
        .then(function (registration)
        {
          console.log('Service worker registered successfully');
        }).catch(function (e)
        {
          console.error('Error during service worker registration:', e);
        });

Tested on Firefox and Chrome.

Refer to the examples in Service worker specification


Service workers are basically a proxy between your web application and the internet, so it can intercept calls to the network if so desired.

Scope in this instance refers to the path that the service worker will be able to intercept network calls from. The scope property can be used explicitly define the scope it will cover. However:

Service workers can only intercept requests originating in the scope of the current directory that the service worker script is located in and its subdirectories. Or as MDN states:

The service worker will only catch requests from clients under the service worker's scope.

The max scope for a service worker is the location of the worker.

As your service worker is located in /static/mod/practice/, it's not allowed to set its scope to /practice/foopage/. Requests to other hosts, e.g. https://stackoverflow.com/foo, can be intercepted in any case.

The easiest way to ensure that your service worker can intercept all the calls it needs to, would be to place it in the root directory of your web app (/). You can also override the default restrictions using an http header and manually setting the scope (see Ashraf Sabry's answer).


For the people who are using nginx it couldn't be any simpler:

# Given that /static is your route to assets
location /static {
        # using / as root scope
        add_header Service-Worker-Allowed /;
....