serviceworker是否可以将标头添加到url请求

Ter*_*how 3 ruby-on-rails service-worker

我有一个我不想让人们创建帐户的网站。它是对每个新闻文章进行分类的新闻提要。我想允许人们标记他们感兴趣的类别,以便下次他们访问该网站时,它仅显示已标记类别的新闻。

我将标签保存在indexedDB中,据我了解该标签可在Service Worker中使用。

因此,在我的服务人员中,我想“拦截”对的请求www.my-url.com,检查indexDB以了解此人感兴趣的类别,并添加一些标头,例如,'x-my-customer-header': 'technology,physics,sports'这样我的服务器就只能使用这些类别的动态html进行响应。

但是,我正在努力让服务工作者正确缓存我的根响应。在我的serviceworker.js中,我event.requestonFetch处理程序控制台记录了每个日志。没有与我的根URL相关的请求。我现在正在本地主机上进行测试,但仅看到对CSS和JS文件的提取请求。

这是我的onFetch:

function onFetch(event) {
  console.log('onFetch',event.request.url);
  event.request.headers["X-my-custom-header"] = "technology,sports";
  event.respondWith(
    // try to return untouched request from network first
    fetch(event.request).catch(function() {
      // if it fails, try to return request from the cache
      caches.match(event.request).then(function(response) {
        if (response) {
          return response;
        }
        // if not found in cache, return default offline content for navigate requests
        if (event.request.mode === 'navigate' ||
          (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
          return caches.match('/offline.html');
        }
      })
    })
  );
}
Run Code Online (Sandbox Code Playgroud)

我使用的是Rails,因此不存在要缓存的index.html,当用户点击我的网址时,该页面将由news#controller动态提供。

我实际上正在使用gem serviceworker-rails

我究竟做错了什么?如何让服务工作者保存一个根文件并拦截添加标头的请求?这有可能吗?

Ant*_*ris 7

感谢Jeff Posnick提出的关于构建新Request的回答。您需要以创建新请求的提取响应,您可以在其中添加标头:

self.addEventListener('fetch', event => {
  event.respondWith(customHeaderRequestFetch(event))
})

function customHeaderRequestFetch(event) {
  // decide for yourself which values you provide to mode and credentials
  const newRequest = new Request(event.request, {
    mode: 'cors',
    credentials: 'omit',
    headers: {
      'x-my-custom-header': 'The Most Amazing Header Ever'
    }
  })
  return fetch(newRequest)
}
Run Code Online (Sandbox Code Playgroud)