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?
1 Answer
Reset to default 12By 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
版权声明:本文标题:javascript - How can we check if response for the request came from Service Worker - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743769732a2535898.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论