Get page URL parameters from a service worker

假如想象 提交于 2019-12-22 00:26:38

问题


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.


回答1:


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.
}



回答2:


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


来源:https://stackoverflow.com/questions/46802864/get-page-url-parameters-from-a-service-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!