Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page URLs in ServiceWorker scope

How can I get the URL of pages that register ServiceWorker in ServiceWorker scope?

main.js

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);
});

sw.js

console.log(self.location.pathname); // /sw.js
// How can I get the `/user` URI?
like image 865
Lewis Avatar asked Apr 16 '15 10:04

Lewis


People also ask

Does service worker work on HTTP?

A service worker intercepts network-type HTTP requests and uses a caching strategy to determine what resources should be returned to the browser.

Do service workers run when browser is closed?

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.

How do I find out if a service is already registered?

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.

What is navigator serviceWorker?

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.


1 Answers

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.

like image 173
Jeff Posnick Avatar answered Oct 06 '22 20:10

Jeff Posnick