admin管理员组

文章数量:1364018

In Google Chrome console next to the status code of HTTP Request we have info (from ServiceWorker).

Can Request be aware somehow that the Response came from ServiceWorker? Comparing date from Response Headers maybe?

In Google Chrome console next to the status code of HTTP Request we have info (from ServiceWorker).

Can Request be aware somehow that the Response came from ServiceWorker? Comparing date from Response Headers maybe?

Share Improve this question edited Sep 8, 2015 at 4:16 sideshowbarker 88.5k30 gold badges215 silver badges212 bronze badges asked May 5, 2015 at 7:10 Karol KlepackiKarol Klepacki 2,1181 gold badge20 silver badges30 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

By design, a response returned via a FetchEvent#respondWith() is meant to be indistinguishable from a response that had no service worker involvement. This applies regardless of whether the response we're talking about is obtained via XMLHttpRequest, window.fetch(), or setting the src= attribute on some element.

If it's important to you to distinguish which responses originated via service worker involvement, the cleanest way I could think of would be to explicitly add an HTTP header to the Response object that is fed into FetchEvent#respondWith(). You can then check for that header from the controlled page.

However, depending on how your service worker is obtaining its Response, that might be kind of tricky/hacky, and I can't say that I remend it unless you have a strong use case. Here's what an (again, not remending) approach might look like:

event.respondWith(
  return fetch(event.request).then(function(response) {
    if (response.type === 'opaque') {
      return response;
    }

    var headersCopy = new Headers(response.headers);
    headersCopy.set('X-Service-Worker', 'true');

    return response.arrayBuffer().then(function(buffer) {
      return new Response(buffer, {
        status: response.status,
        statusText: response.statusText,
        headers: headersCopy
      });
    });
  })
)

If you get back an opaque Response, you can't do much with it other than return it directly to the page. Otherwise, it will copy a bunch of things over into a new Response that has a an X-Service-Worker header set to true. (This is a roundabout way of working around the fact that you can't directly modify the headers of the Response returned by fetch().)

本文标签: javascriptHow can we check if response for the request came from Service WorkerStack Overflow