Reputation: 6969
I have been checking out push notifications for the web and have run into the following snippet
How does this resolve if there are multiple service workers? Does it return the last registered service worker?
The documentation isn't really clear to me on this one.
Upvotes: 8
Views: 3173
Reputation: 56044
Jake Archibald's "The Service Worker Lifecycle" is a fantastic resource, and if you haven't read it, I recommend doing so.
Each service worker has its own scope. By default, and at its most permissive, the scope is the same directory that the service worker script is served from. If needed, you can pass in a more restrictive scope when you call navigator.serviceWorker.register()
.
It's possible to register multiple service workers with different scopes for a given origin. (Aside: If you try to register multiple service workers with the same scope for a given origin, even if the service workers have different URLs, the subsequent registrations will be treated like service worker updates, not as separate registrations.)
If multiple service workers are registered, then in order to determine which one controls a give client page, the scopes are checked. The service worker whose registered scope is most specific, i.e. is the longest matching scope, is the one which will control a given client page.
So, for example, given the following two service worker registrations with corresponding scopes:
/path/to/sw.js
, registered with scope /path/to/
/path/to/subdir/sw.js
, registered with scope /path/to/subdir/
If the client page's URL is /path/to/index.html
, then SW 1 will control the client, since /path/to/
is the longest matching scope.
If the client page's URL is /path/to/subdir/index.html
, then SW 2 will control the client. Even though SW 1's scope matches, SW 2's scope matches as well, and SW 2's scope is more specific/longer.
Upvotes: 15