[PWA] 6. Hijacking response

时间:2023-11-30 11:26:50

For example, if the url is not match to any API endpoint, we want to return 404 error message.

So first thing, we want to send the request to the server first. If got the response, then we just return it back.

self.addEventListener('fetch', (event) => {

    event.respondWith(
fetch(event.request).then( (response) => {
// fetch the request frist return response;
})
)
});

Then we handle 404 error:

self.addEventListener('fetch', (event) => {

    event.respondWith(
fetch(event.request).then( (response) => {
if(response.status === ){
return fetch('/img/dr-evil.gif');
} return response;
}).catch( () => {
return new Response("Something totally wrong");
})
)
});