Firefox、服务人员和后退按钮
我收到报告说,在最新版本的Firefox中,按Back会导致My ServiceWorker提供的"You Are Offline"页面出现。
以下是ServiceWorker的功能部分:
self.addEventListener('fetch',function(event) {
// We only want to call event.respondWith() if this is a navigation request
// for an HTML page.
// request.mode of 'navigate' is unfortunately not supported in Chrome
// versions older than 49, so we need to include a less precise fallback,
// which checks for a GET request with an Accept: text/html header.
if (event.request.mode === 'navigate' ||
(event.request.method === 'GET' &&
event.request.headers.get('accept').includes('text/html'))) {
event.respondWith(
fetch(event.request).catch(function(error) {
// The catch is only triggered if fetch() throws an exception, which will most likely
// happen due to the server being unreachable.
// If fetch() returns a valid HTTP response with an response code in the 4xx or 5xx
// range, the catch() will NOT be called. If you need custom handling for 4xx or 5xx
// errors, see https://github.com/GoogleChrome/samples/tree/gh- pages/service-worker/fallback-response
return caches.match(OFFLINE_URL);
})
);
}
// If our if() condition is false, then this fetch handler won't intercept the request.
// If there are any other fetch handlers registered, they will get a chance to call
// event.respondWith(). If no fetch handlers call event.respondWith(), the request will be
// handled by the browser as if there were no service worker involvement.
});
因此,由于某种原因,在Firefox中,按Back返回的是OFFLINE_URL
而不是目标页面。
这可能是什么原因造成的,我该如何进行调试?
解决方案
火狐在使用"后退"按钮时,显然有一个Chrome没有的额外步骤。
它执行一个"只有在缓存的情况下"的请求,这当然会失败,因为页面没有缓存(它们都是动态的)。由于失败,它会抛出一个错误,并调用catch
。
添加此检查已修复:
&& event.request.cache !== 'only-if-cached'
这使Firefox能够意识到资源未缓存,并照常继续。
相关文章