Skip to content

Instantly share code, notes, and snippets.

@chenhunghan
Last active December 14, 2017 12:27
Show Gist options
  • Save chenhunghan/d50d3ac63a6a5f41999cd7f5a0b38c75 to your computer and use it in GitHub Desktop.
Save chenhunghan/d50d3ac63a6a5f41999cd7f5a0b38c75 to your computer and use it in GitHub Desktop.
Hijacking Request with Service Worker

Hijacking img requests

self.addEventListerner('fetch', (event) => {
  if (event.request.url.endsWith('.jpg')) {
    event.respondWith(
      fetch('/img/someLocalImage.jpg')
    );
  }
}

Handle 404

self.addEventListerner('fetch', (event) => {
  event.respondWith(
    fetch(event.request).then((response) => {
      if (response.status == 404) {
        return new Response("<h1>Page not found!</h1>", {
          headers: {
            'Content-Type': 'text/html',
          }
        })
      }
      return response;
    }).catch(() => {
      return new Response('Unknow fail');
    })
  )
}

Return assets in cache(s)

self.addEventListerner('fetch', (event) => {
  event.respondWith(
    fetch(event.request).then((response) => {
      if (response.status == 404) {
        return new Response("Page not found!")
      }
      return response;
    }).catch(() => {
      return new Response('Unknow fail');
    })
  )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment