WICG / background-sync

A design and spec for ServiceWorker-based background synchronization
https://wicg.github.io/background-sync/spec/
Apache License 2.0
639 stars 83 forks source link

Sync events only get fired when online. #132

Open lucas42 opened 8 years ago

lucas42 commented 8 years ago

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:

This works well in 2 network conditions:

But it fails drastically in 1 case:

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.

jakearchibald commented 7 years ago

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.

lucas42 commented 7 years ago

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.

MohamedSaydSaleh commented 5 years ago

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

jakearchibald commented 5 years ago

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.