问题
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?
回答1:
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()
.)
来源:https://stackoverflow.com/questions/30046374/how-can-we-check-if-response-for-the-request-came-from-service-worker