0

我无法显示offline.html 页面。我不断得到The FetchEvent for "https://my-domain.com" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".

这是我的 service-worker.js 的片段,它应该offline.html在网络不可用时返回。

self.addEventListener('fetch', function(event) {
     if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
        if(event.request.url.includes("my-domain.com")){
            console.log(event.request);
            event.respondWith(
                caches.match(event.request).then(function(resp) {
                    return resp || fetch(event.request).then(function(response) {
                        let responseClone = response.clone();
                        caches.open(CACHE_NAME).then(function(cache) {
                            cache.put(event.request, responseClone);
                        });
                        return response;
                    });
                }).catch(function() {
                    return caches.match("/offline.html");
                })
            );            
        }
    }
});

下面是我的网络请求的console.log(离线时页面刷新)

Request {method: "GET", url: "https://my-domain.com", headers: Headers, destination: "unknown", referrer: "", …}
bodyUsed:false
cache:"no-cache"
credentials:"include"
destination:"unknown"
headers:Headers {}
integrity:""
keepalive:false
method:"GET"
mode:"navigate"
redirect:"manual"
referrer:""
referrerPolicy:"no-referrer-when-downgrade"
signal:AbortSignal {aborted: false, onabort: null}
url:"https://my-domain.com"
__proto__:Request
4

1 回答 1

5

我得到了这个工作/找到了修复。它与浏览器中的重定向响应安全问题有关。来自 Chromium Bugs 博客,Response.redirected 和一个新的安全限制

解决方案:为避免此故障,您有 2 个选项。

  1. 您可以更改安装事件处理程序以存储从 res.body 生成的响应:

    self.oninstall = evt => {
      evt.waitUntil(
          caches.open('cache_name')
            .then(cache => {
                return fetch('/')
                  .then(response => cache.put('/', new Response(response.body));
              }));
    };
    
  2. 或者通过将重定向模式设置为“手动”来更改两个处理程序以存储非重定向响应:

    self.oninstall = function (evt) {
      evt.waitUntil(caches.open('cache_name').then(function (cache) {
        return Promise.all(['/', '/index.html'].map(function (url) {
          return fetch(new Request(url, { redirect: 'manual' })).then(function (res) {
            return cache.put(url, res);
          });
        }));
      }));
    };
    self.onfetch = function (evt) {
      var url = new URL(evt.request.url);
      if (url.pathname != '/' && url.pathname != '/index.html') return;
      evt.respondWith(caches.match(evt.request, { cacheName: 'cache_name' }));
    };
    
于 2018-07-03T20:20:04.070 回答