Handling redirects with a Service Worker

request = new Request(url, {
method: 'GET',
headers: request.headers,
mode: request.mode == 'navigate' ? 'cors' : request.mode,
credentials: request.credentials,
redirect: request.redirect
});
// For HTML requests, try the network first, fall back to the cache, finally the offline page
if (request.headers.get('Accept').indexOf('text/html') !== -1) {
event.respondWith(
fetch(request)
.then( response => {
// NETWORK
// Stash a copy of this page in the pages cache
let copy = response.clone();
stashInCache(pagesCacheName, request, copy);
return response;
})
.catch( () => {
// CACHE or FALLBACK
return caches.match(request)
.then( response => response || caches.match('/offline') );
})
);
return;
}
// For HTML requests, try the network first, fall back to the cache, finally the offline page
if (request.headers.get('Accept').indexOf('text/html') !== -1) {
request = new Request(url, {
method: 'GET',
headers: request.headers,
mode: request.mode == 'navigate' ? 'cors' : request.mode,
credentials: request.credentials,
redirect: request.redirect
});
event.respondWith(
fetch(request)
.then( response => {
// NETWORK
// Stash a copy of this page in the pages cache
let copy = response.clone();
stashInCache(pagesCacheName, request, copy);
return response;
})
.catch( () => {
// CACHE or FALLBACK
return caches.match(request)
.then( response => response || caches.match('/offline') );
})
);
return;
}

--

--

A web developer and author living and working in Brighton, England. Everything I post on Medium is a copy — the originals are on my own website, adactio.com

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store