URL of page currently being served by Service Worker 'fetch' event

陌路散爱 提交于 2019-11-29 16:04:31

You've got two general approaches, depending on how involved you want to get:

Use the 'Referer' header info

If the request is for a subresource and includes a Referer header, then there's a decent chance that the value of that header is the URL of the page that made the request. (There are some caveats; read this background info to delve into that.)

From within a fetch handler, you can read the value of that header with the following:

self.addEventListener('fetch', event => {
  const clientUrl = event.request.referrer;
  if (clientUrl) {
    // Do something...
  } 
});

Use the clientId value

Another approach is to use the clientId value that (might) be exposed on the FetchEvent, and then use clients.get(id) or loop through the output of clients.matchAll() to find the matching WindowClient. You could then read the url property of that WindowClient.

One caveat with this approach is that the methods which look up the WindowClient are all asynchronous, and return promises, so if you're somehow using the URL of the client window to determine whether or not you want to call event.respondWith(), you're out of luck (that decision needs to be made synchronously, when the FetchEvent handler is first invoked).

There's a combination of different things that need to be supported in order for this approach to work, and I'm not sure which browsers currently support everything I mentioned. I know Chrome 67 does, for instance (because I just tested it there), but you should check in other browsers if this functionality is important to you.

self.addEventListener('fetch', async event => {
  const clientId = event.clientId;
  if (clientId) {
    if ('get' in clients) {
      const client = await clients.get(clientId);
      const clientUrl = client.url;
      // Do something...
    } else {
      const allClients = await clients.matchAll({type: 'window'});
      const filtered = allClients.filter(client => client.id === clientId);
      if (filtered.length > 0) {
        const clientUrl = filtered[0].url;
        // Do something...
      }
    }
  }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!