Service Worker Scope
Remember early on when I said that one of the requirements for PWAs was that the browser accesses the app using a TLS (HTTPS) or localhost connection? This layer of security helps protect apps from rogue agents loading a service worker from another location.
As another layer of security, the location of the service worker file matters. When an app registers a service worker, by default the service worker can work only with resources hosted in the same folder location and below; anything higher up in the folder structure is ignored.
If you remember the code that registers the app’s service worker (Listing 3.2), when registration completes successfully, the code executes the following line:
console.log(`Service Worker Registration (Scope: ${reg.scope})`);
This lets the developer know that the service worker registered correctly, and it outputs the contents of the reg object’s scope property:
Service Worker Registration (Scope: http://localhost:3000/)
This scope defines the service worker’s operational domain, the part of the web app over which the service worker has providence. In this example, the service worker scope begins at localhost and covers anything available under that host.
If your app includes content and code in subfolders, for example, app1 and app2, and you want to register a separate service worker for each, you can easily do that. One option is to place the appropriate service worker in each folder; they automatically inherit scope from the folder where the service worker code is hosted when you register the service worker.
Another option is to set the scope for the service worker during registration; as an example, look at the following code:
navigator.serviceWorker.register('/sw1.js', {scope: '/app1/'})
This example registers the sw1.js service worker and sets the scope for the service worker to the app1 folder. With this in place, this service worker will process fetch requests only for resources located in the app1 folder and below (subfolders).