Reputation: 13216
I have a complicated service worker. When it's installing, its initial setup behaviour needs to change depending on whether there's already another service worker that's in place for the origin.
Is it possible to detect from within a service worker, preferably during the install
event, whether another service worker is already active?
From within the page context it looks like I could use navigator.serviceWorker.getRegistrations()
, but navigator.serviceWorker
is undefined inside the service worker itself.
Upvotes: 0
Views: 624
Reputation: 56044
Assuming you do not change the URL or scope of your service worker in between deployments, you should be able to get that information from self.registration
.
self.addEventListener('install', (event) => {
const {installing, waiting, active} = self.registration;
// Since we're in the install handler, `installing` should
// be set to the SW whose global state is `self`.
// `waiting` is likely to be `null`, unless there happened to be a SW
// that was waiting to activate at the point this SW started install.
// `active` is what you're most interested in. If it's null, then there
// isn't already an active SW with the same registration info.
// If it's set to a SW, then you know that there is one.
});
Upvotes: 1