我无法显示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
答案 0 :(得分:0)
我可以正常工作/找到了解决方法。它与浏览器中的重定向响应安全性问题有关。来自Chromium Bugs博客,Response.redirected and a new security restriction。
解决方案:为避免此故障,您有2个选择。
您可以更改安装事件处理程序以存储从res.body生成的响应:
self.oninstall = evt => { evt.waitUntil( caches.open('cache_name') .then(cache => { return fetch('/') .then(response => cache.put('/', new Response(response.body)); })); };
或通过将重定向模式设置为“手动”来更改两个处理程序以存储非重定向响应:
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' })); };