Showing posts with label service worker. Show all posts
Showing posts with label service worker. Show all posts

Friday, March 2, 2018

index.js for service worker hijacking requests 1, 2, and 3

The code below responds with a Dr Evil GIF no matter what:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch('/imgs/dr-evil.gif')
  );
});


The code below only responds with a Dr. Evil GIF where the request ends with .JPG:

self.addEventListener('fetch', function(event) {
  if (event.request.url.endsWith('.jpg')) {
    event.respondWith(
      fetch('/imgs/dr-evil.gif')
    );
  }
});


The code below responds with icon.png where the request ends with .JPG:

self.addEventListener('fetch', function(event) {
  if (event.request.url.endsWith('.jpg')) {
    event.respondWith(
      //fetch('/imgs/dr-evil.gif')
      fetch('/imgs/icon.png')
    );
  }
});


The code below responds with one message when the URL is not found and another message when we completely have no WiFi at all:

self.addEventListener('fetch', function(event) {
    event.respondWith(

    fetch(event.request)

    .then(function(response) {
      if (response.status === 404) {
        // TODO: instead, respond with the gif at
        // /imgs/dr-evil.gif
        // using a network request
        //fetch('/imgs/dr-evil.gif')
        return new Response("Whoops, not found");
      }
      return response;
    })

    .catch(function() {
      return new Response("Uh oh, that totally failed!");
    }) 

  );

});


The code below is the same as the code above except instead of responding with new Response("Whoops, not found") we responds with fetch('/imgs/dr-evil.gif') when the URL is not found and another message when we completely have no WiFi at all:

self.addEventListener('fetch', function(event) {
    event.respondWith(

    fetch(event.request)

    .then(function(response) {
      if (response.status === 404) {
        // TODO: instead, respond with the gif at
        // /imgs/dr-evil.gif
        // using a network request
        //return new Response("Whoops, not found");
        return fetch('/imgs/dr-evil.gif');
      }
      return response;
    })

    .catch(function() {
      return new Response("Uh oh, that totally failed!");
    }) 

  );

});


https://classroom.udacity.com/courses/ud899-gwg/lessons/6381510081/concepts/63885494460923


https://classroom.udacity.com/courses/ud899-gwg/lessons/6381510081/concepts/63885494490923