从服务工作者获取页面URL参数

Eth*_*han 1 javascript url url-parsing url-parameters service-worker

如何从服务工作者获取带有参数的页面URL?

我试过了,self.registration.scope但不包括参数.

Jef*_*ick 6

我不清楚你是否要求获取服务工作者脚本的URL,或者在服务工作者范围内打开的所有客户端页面的URL.那么......以下是两种方法:

// 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);
  }
});
Run Code Online (Sandbox Code Playgroud)

在任何一种情况下,一旦有了URL对象,如果您对查询参数感兴趣,可以使用它的searchParams属性:

if (url.searchParams.get('key') === 'value') {
  // Do something if the URL contains key=value as a query parameter.
}
Run Code Online (Sandbox Code Playgroud)