Reputation:
I'm trying to use a service worker to do the following tasks:
I have the following code:
this.addEventListener('install', function(event) {
console.log('Service Worker: Installing');
event.waitUntil(
caches.open('v1').then(function(cache) {
console.log('Service Worker: Caching Files');
return cache.addAll([
'/assets/logo.svg',
'/assets/app.css',
'/assets/app.js',
'/assets/common.js',
'/offline.html'
]);
})
);
});
this.addEventListener('fetch', function(event) {
if (event.request.method != "GET" || event.request.mode == "cors" || event.request.url.startsWith('chrome-extension')) return;
console.log('Event to be passed', event);
event.respondWith(
caches.open('v1').then(function(cache) {
return cache.match(event.request).then(function(response) {
if (response) {
console.log('Service Worker: Returning Cached Response', response);
return response;
} else {
fetch(event.request).then(function(response) {
console.log('Service Worker: Returning Response from Server', response);
cache.put(event.request, response.clone());
return response;
}).catch((error) => {
console.log('Fetch failed; returning offline page instead.', error);
return caches.match('/offline.html');
});
}
});
})
);
});
this.addEventListener('activate', function activator(event) {
console.log('Service Worker: Activating', event);
event.waitUntil(
caches.keys().then(function(keys) {
return Promise.all(keys
.filter(function(key) {
return key.indexOf('v1') !== 0;
})
.map(function(key) {
return caches.delete(key);
})
);
})
);
});
The issue I have is that even when offline I get a 200 response for my request, even though I'm offline and not actually retrieving the file.
I understand this is one of the pre-requisites for a PWA to always return a 200 response, but how can I return an offline page if my response always returns as 200.
Any help, advice or resources on service workers would be useful.
Cheers.
Upvotes: 2
Views: 2925
Reputation: 2058
you must handle all events, you can't just "return" if nothing special should happen.
this.addEventListener('fetch', function(event) {
if (event.request.method != "GET" || event.request.mode == "cors" || event.request.url.startsWith('chrome-extension')){
event.respondWith(fetch(event.request));
return;
}
....
then you must also return your fetch event, otherwise you break the promise chain.
} else {
return fetch(event.request).then(function(response) {
Upvotes: 0