是否可以修改 service worker 缓存响应 headers?

is it possible to modify service worker cache response headers?

我正在尝试标记存储在服务工作者缓存中的资源。

我认为可以向资源添加自定义 header 来指示这一点,但是,一旦资源存储在 service worker 中,header 修改似乎会被删除缓存。是这样吗?我在 cache spec 中没有看到任何关于修改响应 header 的内容。

这是我尝试过的示例:

// 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
});

我还尝试删除自定义 headers,修改现有 headers,并创建 new Response() 响应 object 而不是获取现有响应。

编辑:我正在使用 Chrome 56。

您必须创建一个新的响应才能执行此操作:

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));
});

Live demo(查看控制台)