Skip to content

Instantly share code, notes, and snippets.

@bakoushin
Created February 1, 2018 08:14
Show Gist options
  • Save bakoushin/8171c66e1514f9b6588e1d76d5b4bd77 to your computer and use it in GitHub Desktop.
Save bakoushin/8171c66e1514f9b6588e1d76d5b4bd77 to your computer and use it in GitHub Desktop.
ServiceWorker Fetch Examples — Hijacking Requests
self.addEventListener('fetch', event => {
/*
HIJACKING RESPONSE EXAMPLES
Uncomment examples one by one to see how it works.
Don't forget to enable 'Update on reload' in Application - Service Workers.
*/
// Example 1: respond with arbitrary HTML
event.respondWith(
new Response('<h1>Hello, world!</h1>', {
headers: {
'Content-Type': 'text/html; charset=utf-8'
}
})
);
// Example 2: respond with arbitrary fetch()
/*
event.respondWith(
fetch('https://cdn.glitch.com/69cbdbda-3055-43c9-b36a-3e58bdcac373%2Fcat2.jpg?1513506808403')
);
*/
// Example 3: hijack *.jpg requests
/*
if (event.request.url.match(/\.jpg(?:\?.*)?$/i)) {
event.respondWith(
fetch('https://cdn.glitch.com/69cbdbda-3055-43c9-b36a-3e58bdcac373%2Fcat2.jpg?1513506808403')
);
}
*/
// Example 4: respond with arbitrary 404 or connection error
// 1. Update service worker and try to open a page that doesn't exist.
// 2. Turn off internet connection and try to reload a site
/*
event.respondWith(
fetch(event.request)
.then(response => {
if (response.status == 404) {
return new Response('<h1>Whoops, not found!</h1>', {
headers: {
'Content-Type': 'text/html; charset=utf-8'
}
});
};
return response;
}).catch(err => {
return new Response('<h1>Uh oh, that totally failed!</h1>', {
headers: {
'Content-Type': 'text/html; charset=utf-8'
}
});
})
);
*/
// Example 5: respond to 404 with image fetched out of network
// 1. Update service worker and try to open a page that doesn't exist.
// 2. Turn off internet connection and try to reload a site
/*
event.respondWith(
fetch(event.request)
.then(response => {
if (response.status == 404) {
return fetch('https://cdn.glitch.com/69cbdbda-3055-43c9-b36a-3e58bdcac373%2Fcat3.jpg?1513506954183');
};
return response;
}).catch(err => {
return new Response('<h1>Uh oh, that totally failed!</h1>', {
headers: {
'Content-Type': 'text/html; charset=utf-8'
}
});
})
);
*/
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment