Background Sync (one-off)
When a user does something offline (sends a message, saves a form), you store it locally and ask the browser to wake your service worker when the connection is back, even if the tab has been closed.
// In the page, after saving the item to IndexedDB
const reg = await navigator.serviceWorker.ready;
if ('sync' in reg) await reg.sync.register('send-outbox');
else flushOutbox(); // fallback: try now, and again on 'online'
// In the service worker
self.addEventListener('sync', (event) => {
if (event.tag === 'send-outbox') event.waitUntil(flushOutbox());
});
If flushOutbox() rejects, the browser retries later with back-off, a few times. Workbox's BackgroundSyncPlugin wraps this pattern for failed fetch requests.
Periodic Background Sync
Lets an installed app refresh content in the background at intervals, for example to download today's articles before the morning commute.
const status = await navigator.permissions.query({ name: 'periodic-background-sync' });
if (status.state === 'granted') {
await reg.periodicSync.register('refresh-news', { minInterval: 12 * 60 * 60 * 1000 });
}
self.addEventListener('periodicsync', (event) => {
if (event.tag === 'refresh-news') event.waitUntil(refreshNews());
});
The browser decides when it actually runs, based on how much the user engages with the site, the network and battery. Expect at most about once a day for most apps.
Support
Both APIs are Chromium-only (Chrome, Edge, Samsung Internet, Opera). Safari and Firefox do not support them. So:
- Always keep a fallback: flush the outbox on
online, onvisibilitychangeand on app start. - Never make background sync the only way data gets sent.
See offline-first data for the full outbox pattern.
Compatibilidad de navegadores
| Función | Chrome / Edge desktop | Chrome Android | Safari iOS / iPadOS | Safari macOS | Firefox desktop | Firefox Android | Samsung Internet |
|---|---|---|---|---|---|---|---|
| Background Sync | Chrome / Edge desktop: Sí | Chrome Android: Sí | Safari iOS / iPadOS: No | Safari macOS: No | Firefox desktop: No | Firefox Android: No | Samsung Internet: Sí |
| Periodic Background Sync | Chrome / Edge desktop: Sí (Installed apps, engagement-based) | Chrome Android: Sí (Installed apps, engagement-based) | Safari iOS / iPadOS: No | Safari macOS: No | Firefox desktop: No | Firefox Android: No | Samsung Internet: Depende |