简体   繁体   中英

How can we check if response for the request came from Service Worker

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?

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 recommend it unless you have a strong use case. Here's what an (again, not recommending) 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() .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM