我收到报告称,在最新版本的 Firefox 中,按下返回会导致显示由我的 ServiceWorker 提供的“您处于离线状态”页面。
这是 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 中,按返回键会返回 OFFLINE_URL
而不是预期的页面。
可能是什么原因造成的,我应该如何调试它?
最佳答案
当使用“后退”按钮时,Firefox 显然有一个 Chrome 没有的额外步骤。
它执行“仅当缓存”请求时,该请求当然会失败,因为页面未缓存(它们都是动态的)。由于失败,它会抛出错误,并调用 catch
。
添加此检查修复它:
&& event.request.cache !== 'only-if-cached'
这让 Firefox 意识到资源没有被缓存,并照常进行。
关于javascript - Firefox、service workers 和后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49985384/