Skip to content

Instantly share code, notes, and snippets.

@aminukano585
Forked from bakoushin/sw.js
Created June 5, 2018 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aminukano585/d67a9e60e63bb0fc3f63fb02b264b193 to your computer and use it in GitHub Desktop.
Save aminukano585/d67a9e60e63bb0fc3f63fb02b264b193 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