Skip to content

Instantly share code, notes, and snippets.

@luke-denton-aligent
Last active November 16, 2016 04:02
Show Gist options
  • Save luke-denton-aligent/0a0a9807e3360bae3148eed820e598ec to your computer and use it in GitHub Desktop.
Save luke-denton-aligent/0a0a9807e3360bae3148eed820e598ec to your computer and use it in GitHub Desktop.
This snippet shows how to make a network call as normal, but before sending it to the browser, inspecting it and performing another action
// Offline Web Applications course on Udacity https://classroom.udacity.com/courses/ud899
self.addEventListener('fetch', function(event) {
event.respondWith(
//Make the request call as the browser would normally
fetch(event.request).then(function(reponse) {
//Check if the status is a 404, returning a custom response if true
if (response.status === 404) {
return new Response("Whoops, not found!");
}
//Alternative option
//If the status is 404, respond with the superman.jpg image
if (response.status === 404) {
return fetch("imgs/superman.jpg");
}
//If the response wasn't a 404, then just return it normally, essentially meaning nothing has changed from a normal browser request
return response;
}).catch(function() {
return new Response("Uh oh, that totally failed!");
});
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment