简体   繁体   中英

Firefox, service workers and the Back button

I'm getting reports that in the latest version of Firefox, pressing Back causes the "you are offline" page, provided by my ServiceWorker, to appear.

Here's the functional part of the 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.
});

So for some reason, in Firefox, pressing Back is returning the OFFLINE_URL instead of the intended page.

What could be causing this, and how might I go about debugging it?

Firefox apparently has an extra step that Chrome does not, when using the Back button.

It performs a request "only-if-cached", which of course fails since the pages aren't cached (they are all dynamic). Since it fails, it throws an error, and the catch is called.

Adding this check fixed it:

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

This allows Firefox to realise that the resource is not cached, and proceed as normal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM