Reputation: 11
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
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));
}
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?
Upvotes: 1
Views: 2738
Reputation: 56044
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.
});
Upvotes: 2