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?
A service worker intercepts network-type HTTP requests and uses a caching strategy to determine what resources should be returned to the browser.
Service workers have a total control over every request made from a website. Since they run in the background, they don't need the webpage to be open. That gives them ability to listen and respond to events such as push messages sent from the server to the browser.
You can look at Service Worker Detector, a Chrome extension that detects if a website registers a Service Worker by reading the navigator. serviceWorker. controller property. It might also work in other browsers supporting Web Extensions, but it looks like it is not yet distributed as such.
The Navigator. serviceWorker read-only property returns the ServiceWorkerContainer object for the associated document, which provides access to registration, removal, upgrade, and communication with the ServiceWorker . The feature may not be available in private mode.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With