Search code examples
service-workerprogressive-web-appsworkbox

Force a POST to Background sync regardless of current connectivity - behaviour on Firefox and Safari?


So I've managed to implement Background Sync with Workbox, working beautifully on Chrome. Rather than wait for a fetch to fail, I'm immediately pushing it into the bg sync queue - so that users will never have to wait for an image upload, even if they have network connectivity.

Now, on Safari and Firefox - I understand the fallback will be to attempt a background sync every time the service worker starts. However, in this case the service worked has not stopped because there has not been an interruption in network service. Does this mean I will only get this item uploaded the next time the browser is started, or the specific PWA is started, or the URL is refreshed?


Solution

  • To answer your question, it's impossible to know for sure when a service worker will stop running. Each browser will stop a service worker after a period of time without any events, and then start up the service worker again the next time there's an event it needs to handle (fetch, sync, etc.) But each browser implements that exact timing differently.

    Workbox's background sync implementation does have a manual method that could be called to start processing items in the queue on demand.

    That being said, I would not recommend interacting with the background sync queue in that fashion.

    Actually attempting the upload, and then only adding items to the background sync queue upon failure (automatically, via the BackgroundSyncPlugin would be easiest) is the recommended usage.

    The behavior you really want, in which uploads "happen in the background", is enabled via background fetch. Unfortunately, background fetch is also only available in Chrome at this time. I'm not sure that trying to simulate background fetch in browsers that don't support it, and don't support background sync, is going to give non-Chrome users a great experience.