javascript - Firefox、service workers 和后退按钮

标签 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 中,按返回键会返回 OFFLINE_URL 而不是预期的页面。

可能是什么原因造成的,我应该如何调试它?

最佳答案

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

它执行“仅当缓存”请求时,该请求当然会失败,因为页面未缓存(它们都是动态的)。由于失败,它会抛出错误,并调用 catch

添加此检查修复它:

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

这让 Firefox 意识到资源没有被缓存,并照常进行。

关于javascript - Firefox、service workers 和后退按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49985384/

相关文章:

c# - 将数据绑定(bind)到kendo下拉列表时如何获取变量的ajax响应数据?

javascript - 为什么用户登录后导航栏组件不更新? (无 Redux)

javascript - chrome 中的事件.dataTransfer.dropEffect

firefox - Firefox扩展和Firefox插件之间有什么区别?

javascript - SW-Toolbox 防止加载跨源视频

ruby-on-rails - 如何在 Ruby on Rails 中注册服务 worker ?

javascript - 如何在AJAX中输出Json数据

javascript - PushState 在不应该执行的时候执行

firefox - 在 x 轴上使用时间刻度的 D3 散点图 - 在 Firefox 中不起作用

javascript - PushSubscription.endPoint 会随着时间的推移而变化吗?