Wish
Wish

Reputation: 1614

ServiceWorker fetch-complete event

Reasone, I am using serviceWorker - is to check the time until cookie ends. Cookie expiration is set to 60 minutes on request.

I built 2 versions of the fetch listener on serviceWorker

This version resets time counter on on the client (by sending a message to it by channel.postMessage. But it sends the trigger on request (not after response).

self.addEventListener( "fetch", event => {
    channel.postMessage(true);
});

The second version creates new fetch call, gets the response, triggers client, and then returns the response.

self.addEventListener( "fetch", event => {
    event.respondWith((async () => {
        const response = await fetch(event.request);
        channel.postMessage(true);
        return response;
    })());
});

In this situation - second option would be more accurate in terms of time. But this creates those duplicate network requests, if looking at network tab in the developer tools duplicate requests

Is it somehow possible, to let the fetch do it's thing, let it complete, and get the response without creating new fetch call? I am not interested in any sort of serviceWorker for caching (100% of the use cases for fetch event in examples are for caching...)

Upvotes: 1

Views: 1239

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56074

There is only one network call being made in this scenario, although Chrome's DevTools Network panel might be a bit confusing and imply otherwise. This answer explains what you're seeing in more detail.

If the only thing you want to do in your fetch handler is call channel.postMessage(), then I would recommend not calling event.respondWith(). If you have another fetch handler registered after your first one, that handler will get its own chance to respond. If none of your fetch handlers call event.respondWith(), then it will effectively be a no-op from a networking perspective.

self.addEventListener('fetch', (event) => {
  // Optional: you might want to check for some criteria
  // before calling channel.postMessage().
  if (event.request.url === '...') {
    channel.postMessage(true);
  }
});

Upvotes: 2

Related Questions