Lesson 15 / 30
Background sync
Implement background sync to reliably deliver user data even if the connection is lost.
Reliable data delivery
Background sync queues user actions (form submissions, file uploads) and retries them when the connection is restored. The browser handles retries, not your app.
Register background sync
Queue a task for background sync and handle it in the service worker.
// In page
navigator.serviceWorker.ready.then(reg => {
reg.sync.register('submit-form').then(() => {
console.log('Sync registered');
});
});
// In service worker
self.addEventListener('sync', event => {
if (event.tag === 'submit-form') {
event.waitUntil(
fetch('/api/submit', { method: 'POST', body: formData })
.catch(() => Promise.reject())
);
}
});
Output:
Form submission retried automatically when connection is restored.
A common trap
Background Sync works only in the service worker and is supported mainly in Chromium browsers, so keep a fallback that retries when the page is open. Failed syncs are retried with backoff.