I am building a progressive web application using Google Workbox. I have setup a service worker with bgSync (in my build folder) so that my POST requests are pushed to a queue and sent to my endpoint when the user regains connection, but when does the syncing event happen exactly?
For development purposes, I use the "Sync" button included in Chrome as detailed in this answer: How to manually trigger a background sync (for testing)?, But this is manual, I'd like the requests to be sent to the endpoint as soon as the application is back online, but when I get connection my requests are not sent, I have to manually click the "Sync" button for that to happen, and it does work beautifully, but users won't be clicking the Sync button in a real scenario.
Precisely, I'd like to know if there is a way, inside my service-worker, to detect when the application is back online, and force a Sync. Or to know when the sync happens. Here is a snippet for reference (Using Workbox 3.0.0):
const bgSyncPlugin = new workbox.backgroundSync.Plugin('myQueue', {
callbacks: {
requestWillEnqueue: (storableRequest) => {}, // I show a push notification indicating user is offline
requestWillReplay: (storableRequest) => {},
queueDidReplay: (storableRequestArray) => {} // If I get a response, I show a push notification
}
},
);
workbox.routing.registerRoute(
"https://myapi.com/action",
workbox.strategies.networkOnly({
plugins: [bgSyncPlugin]
}),
'POST'
);