patternjavascriptModerate
Background sync — deferring actions when offline
Viewed 0 times
Background Sync API (Chrome 49+, Edge 79+)
background syncSyncManageroffline formsservice worker syncIndexedDB offline
browser
Problem
When a user submits a form or triggers an action while offline, the request fails silently and the data is lost. Retry logic in the client page does not work if the user closes the tab before connectivity is restored.
Solution
Use the Background Sync API to register a sync tag and defer the request until connectivity is available, even if the page has been closed.
// In the page — save data locally and register sync
async function submitForm(data) {
// Save to IndexedDB so SW can retrieve it later
await idb.put('pending-submissions', data);
if ('serviceWorker' in navigator && 'SyncManager' in window) {
const reg = await navigator.serviceWorker.ready;
await reg.sync.register('submit-form');
} else {
// Fallback: try immediately
await sendToServer(data);
}
}
// In sw.js — handle the sync event
self.addEventListener('sync', event => {
if (event.tag === 'submit-form') {
event.waitUntil(
idb.getAll('pending-submissions').then(items =>
Promise.all(items.map(item =>
fetch('/api/submit', {
method: 'POST',
body: JSON.stringify(item),
}).then(() => idb.delete('pending-submissions', item.id))
))
)
);
}
});
// In the page — save data locally and register sync
async function submitForm(data) {
// Save to IndexedDB so SW can retrieve it later
await idb.put('pending-submissions', data);
if ('serviceWorker' in navigator && 'SyncManager' in window) {
const reg = await navigator.serviceWorker.ready;
await reg.sync.register('submit-form');
} else {
// Fallback: try immediately
await sendToServer(data);
}
}
// In sw.js — handle the sync event
self.addEventListener('sync', event => {
if (event.tag === 'submit-form') {
event.waitUntil(
idb.getAll('pending-submissions').then(items =>
Promise.all(items.map(item =>
fetch('/api/submit', {
method: 'POST',
body: JSON.stringify(item),
}).then(() => idb.delete('pending-submissions', item.id))
))
)
);
}
});
Why
Background Sync ensures data is not lost when the user is offline. The browser retries the sync tag automatically (with exponential backoff) when connectivity is restored, even if the user has closed the app.
Gotchas
- Background Sync API is Chrome/Edge only (2026) — always provide a fallback for Safari and Firefox
- Sync events retry with increasing intervals — design for idempotent server endpoints to handle duplicate submissions
- Use IndexedDB (or a wrapper like idb) to persist pending data — localStorage is synchronous and unavailable in service workers
- Periodic Background Sync (for routine updates, not user actions) requires site engagement score to be granted by the browser
Context
Forms or user actions that must complete even if connectivity is lost mid-session
Revisions (0)
No revisions yet.