Reputation: 14866
How can I get the URL of pages that register ServiceWorker in ServiceWorker scope?
console.log(window.location.pathname); // /user
navigator.serviceWorker.register('/app/sw.js',{scope : '/user'}).then(function(){
console.log('Service Worker initialised');
}).catch(function(er){
console.log('er.message);
});
console.log(self.location.pathname); // /sw.js
// How can I get the `/user` URI?
Upvotes: 12
Views: 8124
Reputation: 147
Some useful docs on available data:
ServiceWorkerRegistration.scope Read only Returns a unique identifier for a service worker registration. This must be on the same origin as the document that registers the ServiceWorker.
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
Upvotes: 0
Reputation: 56044
Within a service worker, self.registration.scope
will give you the associated scope. This is available in Chrome 42+ (which just became the stable release), so it should be safe to use.
I think you might also be asking about how to get the a reference to all of the active pages that a service worker controls, too? If that's the case, the answer is to use self.clients.matchAll()
(also available in Chrome 42+), which will return a (potentially empty) array of WindowClient
objects, corresponding to each open, controlled page. WindowClient
exposes a url
property with the corresponding URL.
Upvotes: 30