Code

Browser Web APIs

CDEFGHIJKLMNOPQRSTUVWXYZ

Background Synchronization API

Experimental

Allows web applications to defer tasks to be run in a service worker until the user has a stable network connection. Ideal for ensuring data submitted while offline is eventually sent to the server.

MDN Reference

Key Interfaces
  • ServiceWorkerRegistration.sync — Returns the SyncManager for the registration.
  • SyncManager.register(tag) — Registers a sync event with the given tag. Returns a Promise.
  • SyncManager.getTags() — Returns a Promise resolving to an array of registered sync tag strings.
  • SyncEvent — Fired in the service worker with a tag property identifying which sync task to run.
Example — Register a sync from the page

Register a sync tag when the user submits a form offline. The service worker will run the sync as soon as connectivity is restored.

async function saveFormData(data) {
  // Persist data locally (e.g. IndexedDB) first
  await saveToIndexedDB(data);

  // Request a background sync
  const registration = await navigator.serviceWorker.ready;
  await registration.sync.register('submit-form');

  console.log('Sync registered — will send when online');
}
Example — Handle the sync event in the service worker

The browser fires the sync event in the service worker when the network is available. If the handler throws, the browser retries.

// service-worker.js
self.addEventListener('sync', (event) => {
  if (event.tag === 'submit-form') {
    event.waitUntil(sendPendingForms());
  }
});

async function sendPendingForms() {
  const pendingItems = await getFromIndexedDB('pending-forms');

  for (const item of pendingItems) {
    const response = await fetch('/api/submit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(item),
    });

    if (response.ok) {
      await removeFromIndexedDB('pending-forms', item.id);
    } else {
      // Throwing causes the browser to retry the sync later
      throw new Error('Server returned ' + response.status);
    }
  }
}
Example — List registered sync tags
const registration = await navigator.serviceWorker.ready;
const tags = await registration.sync.getTags();

console.log('Pending syncs:', tags);
// e.g. ["submit-form", "upload-photo"]