Firefox,服务工作者和后退按钮

时间:2018-04-23 16:03:00

标签: javascript firefox service-worker

我收到的报告显示,在最新版本的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中,按Back键会返回OFFLINE_URL而不是预期的页面。

导致这种情况的原因是什么,我该如何进行调试呢?

1 个答案:

答案 0 :(得分:2)

当使用“后退”按钮时,Firefox显然还有一个额外的步骤。

它执行“only-if-cached”请求,当然因为页面没有被缓存而失败(它们都是动态的)。由于它失败,它会抛出一个错误,并调用catch

添加此检查修复了它:

&& event.request.cache !== 'only-if-cached'

这允许Firefox意识到资源没有被缓存,并且正常进行。