1

I want my Angularjs (1.x) application to have an offline version as fallback in case there is no network or no internet service.

I want the service worker's fetch event listener, try to fetch the main page from the network (when the request.mode == 'navigate') and return the a cached version if it fails.

For some reason, even though I've disconnected the wifi or run in "airplane mode" the fetch always returns StatusCode 200 OK. But it does work indeed, if I turn on Chrome's DevTools "Network > offline" mode

...What I've tried:

I've tried detecting offline mode with "navigator.onLine" feature, but is not reliable.

Also tried to clear cache, but nothing.. still returns the original "online" html document..

Also tried to pass a "cache-control: no-store, no-cache" header to the fetch, with same result..

self.addEventListener('fetch', function (event) {
  if (event.request.mode === 'navigate') {    
    event.respondWith(homeNetworkThenCache(event.request));
  } 
});

function homeNetworkThenCache(request){
  return fetch(request)
          .then(e => e)
          .catch(() => caches.match(offlineHomepageUrl));
}

Expected behavior:

If there's no internet connection, I expect the fetch to enter the "catch" block, but it always enters the ".then(e => e)"...

..any ideas, please?

5
  • Are you setting a Cache-Conrtol header on your HTML responses? It sounds like you might end up reading those responses from the browser's "normal" HTTP cache. Commented Nov 4, 2019 at 21:58
  • The request is made by the browser when you enter the url.. I don't see any "Cache-control" header on the response. The request sends "Cache-Control: max-age=0"
    – JCV
    Commented Nov 5, 2019 at 12:17
  • You're not passing in event.request as a parameter to homeNetworkThenCache(), though? Is that your actual code or did you just paraphrase it? Commented Nov 5, 2019 at 14:43
  • Thanks Jeff.. I've added the event.request param, this was a simplified version, not the exact real code
    – JCV
    Commented Nov 6, 2019 at 8:19

1 Answer 1

2

If you're looking for an example service worker that just implements an offline fallback page, you could use this one, which will also do things like enable navigation preload (if supported):

const OFFLINE_VERSION = 1;
const CACHE_NAME = 'offline';
// Customize this with a different URL if needed.
const OFFLINE_URL = 'offline.html';

self.addEventListener('install', (event) => {
  event.waitUntil((async () => {
    const cache = await caches.open(CACHE_NAME);
    // Setting {cache: 'reload'} in the new request will ensure that the response
    // isn't fulfilled from the HTTP cache; i.e., it will be from the network.
    await cache.add(new Request(OFFLINE_URL, {cache: 'reload'}));
  })());
});

self.addEventListener('activate', (event) => {
  event.waitUntil((async () => {
    // Enable navigation preload if it's supported.
    // See https://developers.google.com/web/updates/2017/02/navigation-preload
    if ('navigationPreload' in self.registration) {
      await self.registration.navigationPreload.enable();
    }
  })());

  // Tell the active service worker to take control of the page immediately.
  self.clients.claim();
});

self.addEventListener('fetch', (event) => {
  // We only want to call event.respondWith() if this is a navigation request
  // for an HTML page.
  if (event.request.mode === 'navigate') {
    event.respondWith((async () => {
      try {
        // First, try to use the navigation preload response if it's supported.
        const preloadResponse = await event.preloadResponse;
        if (preloadResponse) {
          return preloadResponse;
        }

        const networkResponse = await fetch(event.request);
        return networkResponse;
      } catch (error) {
        // catch is only triggered if an exception is thrown, which is likely
        // due to a network error.
        // If fetch() returns a valid HTTP response with a response code in
        // the 4xx or 5xx range, the catch() will NOT be called.
        console.log('Fetch failed; returning offline page instead.', error);

        const cache = await caches.open(CACHE_NAME);
        const cachedResponse = await cache.match(OFFLINE_URL);
        return cachedResponse;
      }
    })());
  }

  // 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.
});
2
  • Thanks Jeff for your effort! really appreciate.. I've tried the 'navigationPreload' feature, I didnt know of that. Nevertheless I cannot resolve the issue yet. I'm almost sure that the network call is returning the http-cached version, as you mentioned earlier. But I dont' know how to bypass it, as the original request also comes from the browser itself (cannot set a no-cache header there)
    – JCV
    Commented Nov 6, 2019 at 8:23
  • Cache-Control headers can be set on either the request or the response. (With different semantics.) While it's the browser making the request, you have control over the server's response, can you can set Cache-Control: no-cache on that response. developer.mozilla.org/en-US/docs/Web/HTTP/Headers/… Commented Nov 7, 2019 at 14:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.