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

可紊 提交于 2019-11-30 09:31:01

问题


How can I get the full URL of the page which is being serviced by a service worker's 'fetch' event?

The "self.location" property seems to only refer to the root URL of the site. For example, if page https://example.com/folder/pagename.html is performing a fetch which the service worker is intercepting, the service worker's 'self.location' property returns "https://example.com".

event.currentTarget.location and event.explicitOriginalTarget.location, event.originalTarget, and event.target all return the URL of the service worker .js file.

How can I get the full URL of the page that triggered the fetch event?


回答1:


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


来源:https://stackoverflow.com/questions/50045641/url-of-page-currently-being-served-by-service-worker-fetch-event

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