4

How do I get page URL with parameters from a service worker?

I have tried self.registration.scope but that doesn't include the parameters.

Ethan
  • 3,410
  • 1
  • 28
  • 49

3 Answers3

9

I'm not clear as to whether you're asking about getting the service worker script's URL, or the URLs of all of the client pages that are open under the service worker's scope. So... here's how to do both:

// Get a URL object for the service worker script's location.
const swScriptUrl = new URL(self.location);

// Get URL objects for each client's location.
self.clients.matchAll({includeUncontrolled: true}).then(clients => {
  for (const client of clients) {
    const clientUrl = new URL(client.url);
  }
});

In either of those cases, once you have a URL object, you can use its searchParams property if you're interested in the query parameters:

if (url.searchParams.get('key') === 'value') {
  // Do something if the URL contains key=value as a query parameter.
}
Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
  • The sample code that I provided that calls `self.clients.matchAll()` will allow you to get the URLs of all the open pages that are in scope of the current service worker. – Jeff Posnick Mar 28 '19 at 16:34
  • My bad, I misread that, the first approach is clearly to get the script's location. Deleting my comment to avoid any further confusion. – aleemb Mar 28 '19 at 18:47
1

You can get waiting.scriptURL or active.scriptURL, pass result to URL() constructor, get .search property of object

  navigator.serviceWorker.register("sw.js?abc=123")
  .then(function(reg) {
    const scriptURL = reg.waiting && reg.waiting.scriptURL || reg.active.scriptURL;
    const url =  new URL(scriptURL);
    const queryString = url.search;
    console.log(queryString);
  }).catch(function(err) {
    console.log("err", err);
  });
guest271314
  • 1
  • 15
  • 104
  • 177
0

ServiceWorker.scriptURL can give you the URL and its parameters as well.

Then, the following step is to get a ServiceWorker object, and it depends on where you would like to use the URL parameters.

In the worker script, use self.serviceWorker.scriptURL. e.g.

const searchParams = new URLSearchParams(self.serviceWorker.scriptURL);

In the page script, use scriptURL with navigator.serviceWorker.ready. e.g.

const serviceWorkerRegistration = await navigator.serviceWorker.ready;
const activeServiceWorker = serviceWorkerRegistration.active;  
const searchParams = new URLSearchParams(activeServiceWorker.scriptURL);

However, you might want to get a registration object from register API, but the above code snippet should work as well.

Sean Lee
  • 21
  • 2