0

I'm using a workbox and trying to cache requests something like this:

this.serviceWorker.addEventListener('fetch', (event) => {
const request = event.request;
event.respondWith(
      caches.open('cache name')
         .then(cache => cache.match(request))
         .then(async (cachedResponse) => {
            // todo something

How Can I cancel event.request and send my custom request? Thanks for any helping.

pate
  • 4,937
  • 1
  • 19
  • 25
Blackbonny
  • 79
  • 2
  • 9

1 Answers1

1

You may alter or completely change the out-going request like so:

this.serviceWorker.addEventListener('fetch', (event) => {
  const request = event.request;
  return event.respondWith(
    caches.open('cache name')
      .then(cache => cache.match(request))
      .then(async (cachedResponse) => {
        // create a new request, fetchi it, and return the result
        return fetch(new Request(request.url ....))
       })

Pay attention to the return statement I added to the third line of code :)

More info about constructing the new request: https://stackoverflow.com/a/35421858/5038943

pate
  • 4,937
  • 1
  • 19
  • 25