是否可以修改 Service Worker 缓存响应标头? [英] is it possible to modify service worker cache response headers?
问题描述
我正在尝试标记存储在 Service Worker 缓存中的资源.
I am trying to mark resources that are being stored in the service worker cache.
我认为可以向资源添加一个自定义标头来表明这一点,但是,一旦将资源存储在 Service Worker 缓存中,标头修改似乎就会被删除.是这种情况吗?我在 缓存规范 中没有看到任何关于修改响应标头的内容.
I thought it would be possible to add a custom header to the resource that could indicate this, however, it appears that header modifications are removed once a resource is stored in the service worker cache. Is this the case? I don't see anything in the cache spec about modifying response headers.
以下是我尝试过的示例:
Here is an example of what I have tried:
// I successfully cache a resource (confirmed in Dev Tools)
caches.open('testCache').then(cache => {
cache.add('kitten.jpg');
})
.then(() => {
console.log('successfully cached image'); // logs as expected
});
// placeholder
var modifiedResponse;
// get the cached resource
caches.open('testCache')
.then(cache => {
return cache.match('kitten.jpg');
})
// modify the resource's headers
.then(response => {
modifiedResponse = response;
modifiedResponse.headers.append('x-new-header', 'test-value');
// confirm that the header was modified
console.log(modifiedResponse.headers.get('x-new-header')); // logs 'test-value'
return caches.open('testCache');
})
// put the modified resource back into the cache
.then((cache) => {
return cache.put('kitten.jpg', modifiedResponse);
})
// get the modified resource back out again
.then(() => {
return caches.match('kitten.jpg');
})
// the modifed header wasn't saved!
.then(response => {
console.log(response.headers.get('x-new-header')); // logs null
});
我还尝试删除自定义标头、修改现有标头以及创建 new Response()
响应对象,而不是获取现有的响应对象.
I have also tried deleting custom headers, modifying existing headers, and creating a new Response()
response object instead of grabbing an existing one.
我使用的是 Chrome 56.
I am using Chrome 56.
推荐答案
您必须创建一个新的响应才能执行此操作:
You would have to create a new response to do this:
fetch('./').then(response => {
console.log(new Map(response.headers));
const newHeaders = new Headers(response.headers);
newHeaders.append('x-foo', 'bar');
const anotherResponse = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: newHeaders
});
console.log(new Map(anotherResponse.headers));
});
现场演示(见控制台)
这篇关于是否可以修改 Service Worker 缓存响应标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!