background-sync icon indicating copy to clipboard operation
background-sync copied to clipboard

Sync events only get fired when online.

Open lucas42 opened this issue 8 years ago • 4 comments

This might sound like a bizarre request, but I'd find it really helpful if sync events were fired when the user agent is offline.

I have media player which downloads a playlist of tracks. The playlist gets stored in a Cache object by my service worker. When the user wants to skip to the next track, a sync event is registered. The sync event handler in the service worker then does two things:

  • Sends a network request to the server to tell it remove the track from its playlist.
  • Modifies the version in the Cache object and removes the track from there too.

This works well in 2 network conditions:

  • Fully online - the server and cached version both get updated
  • poor network (LieFi) - the cached version is updated; the request to the server fails, but that's okay because background sync means it'll get tried again later.

But it fails drastically in 1 case:

  • Fully offline - the event handler just never gets called, so the service worker doesn't have a chance to modify the cached version.

I can probably work around this by having cache handling logic all over the place, but I think it'd be much neater if I could just keep my caching logic in the service worker.

Is there much of a performance impact of firing sync events when offline? Presumably event handlers which just make network requests will fail pretty much immediately because the browser knows not to try talking to the network.

lucas42 avatar Aug 03 '16 02:08 lucas42

I can probably work around this by having cache handling logic all over the place

This feels like the right thing to do. If having your cache logic in the page is bad in terms of code organisation, you could postmessage to the service worker.

jakearchibald avatar Mar 28 '17 07:03 jakearchibald

The way I solved it in the end was to move all my background sync logic into the service worker. The SW intercepts POST requests, does the cache logic it wants to do and then does the exact same POST request to the server via a background sync. (code example) This way I keep all my cache logic together and the degraded path is very simple - no service worker means the original POST request goes straight to the server.

lucas42 avatar Mar 28 '17 23:03 lucas42

any way to get POST request body in Fetch event listener ?

MohamedSaydSaleh avatar Jun 04 '19 19:06 MohamedSaydSaleh

any way to get POST request body in Fetch event listener ?

Depends what format it's in.

const data = await request.formData();
// or
const data = await request.json();
// or
const data = await request.text();

Etc.

jakearchibald avatar Jun 05 '19 06:06 jakearchibald