我们如何检查请求的响应是否来自Service Worker [英] How can we check if response for the request came from Service Worker
问题描述
在Google Chrome控制台中,HTTP Request
的状态代码旁,我们有信息(from ServiceWorker)
.
Request
能否以某种方式知道Response
来自ServiceWorker吗?比较Response Headers
中的date
吗?
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?
推荐答案
通过设计,通过FetchEvent#respondWith()
返回的响应与没有服务人员参与的响应是无法区分的.不管我们正在讨论的响应是通过XMLHttpRequest
,window.fetch()
还是在某些元素上设置src=
属性获得的,这都适用.
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.
如果对您区分哪个响应是由服务人员参与引起的,这一点很重要,那么我能想到的最简洁的方法是将HTTP标头显式添加到馈入FetchEvent#respondWith()
的Response
对象中.然后,您可以从受控页面检查该标题.
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.
但是,这取决于您的服务工作者如何获得其Response
,这可能会有些棘手/令人毛骨悚然,除非您有强大的用例,否则我不能说我建议这样做.这是一种(再次,不推荐使用)方法:
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
});
});
})
)
如果返回不透明的Response
,除了直接将其返回到页面之外,您将无法执行其他任何操作.否则,它将把一堆东西复制到新的Response
中,该Response
的X-Service-Worker
标头设置为true
. (这是解决无法直接修改fetch()
返回的Response
的headers
的事实的一种回旋方式.)
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()
.)
这篇关于我们如何检查请求的响应是否来自Service Worker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!