user6609184
user6609184

Reputation: 211

fetch not working in service worker

i tried to use the fetch event in service worker but he didnt work for me.

self.addEventListener('activate', function(event) {
  console.log('Activated', event);
  fetch('/embed_testing/notification/main.js').then(response => 
          function () {
              console.log(response)
          });
});

self.addEventListener('fetch', function(event) {
    console.log("heyyyo");
  if (event.request.url === new URL('/', location).href) {
    event.respondWith(
      new Response("<h1>Hello!</h1>", {
        headers: {'Content-Type': 'text/html'}
      })
    )
  }
});

any ideas why it is not working ?

Upvotes: 0

Views: 3871

Answers (2)

Yuar
Yuar

Reputation: 1

In case you are testing your app in chrome, try to uncheck flag "bypass for network" in dev tools on the "Application" tab (choose "Service workers" on the left side)

Upvotes: -1

Jeff Posnick
Jeff Posnick

Reputation: 56144

A fetch() request made from inside a service worker won't trigger that same service worker's fetch event handler. (If it did, you can easily imagine scenarios in which you got into a recursive loop.)

If you need to quickly test that your fetch event handler is working, which appears to be what you're doing in this case, the easiest approach is probably to just open the JavaScript console in DevTools and manually perform a fetch('/path/to/whatever'). A fetch() made from inside the JavaScript console will trigger a service worker's fetch event handler.

If you're interested in something that's not just a test, but rather sharing logic that's implemented inside of a fetch event handler with code that runs outside of the handler, then the recommended approach would be to refactor the code into a standalone function, and then call that function from both inside the fetch event handler and from wherever else in your service worker that it's relevant.

Upvotes: 3

Related Questions