javascript – 是否可以修改服务工作者缓存响应头?

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

我认为可以向资源添加一个可以指示此情况的自定义标头,但是,一旦资源存储在服务工作缓存中,就会删除标头修改.是这样的吗?我在cache spec中没有看到有关修改响应头的任何内容.

这是我尝试过的一个例子:

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

我还尝试删除自定义标头,修改现有标头,并创建一个新的Response()响应对象,而不是抓取现有的.

编辑:我正在使用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(见控制台)

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...