API in Service Worker
Background Sync API
Published Updated
The Background Sync API lets a page register a named sync on its service worker registration; when the browser decides the device has connectivity, it fires a sync event in the service worker, even if the page that registered it has since closed. It is a Chromium feature (Chrome 49, Edge 79, Samsung Internet 5.0) and is not implemented in Firefox or Safari (BCD api.SyncManager), so provide a fallback for retries in those browsers.
Syntax
Section titled “Syntax”// In the page or in the service worker (needs a window client in Chromium)const registration = await navigator.serviceWorker.ready;await registration.sync.register(tag);const tags = await registration.sync.getTags();
// In the service workerself.addEventListener('sync', (event) => { event.waitUntil(doWork(event.tag, event.lastChance));});register() returns a Promise<void> that fulfils once the registration is stored. Registering a tag that is already pending is a no-op, not an error, so a page may call it on every failed request without bookkeeping. getTags() returns a Promise<string[]> of tags that have not yet fired successfully.
Parameters
Section titled “Parameters”The method takes one string argument; the event exposes two read-only attributes.
| Name | Type | Description |
|---|---|---|
tag |
string |
Identifies the registration. One pending registration exists per tag; the same tag is delivered as SyncEvent.tag. Chromium limits the tag to 10,240 characters. |
SyncEvent.tag |
string |
The tag the browser is firing for. Branch on it when one worker handles several queues. |
SyncEvent.lastChance |
boolean |
true when the browser will not retry this registration again if the waitUntil() promise rejects. Use it to surface the failure to the user instead of retrying. |
Exceptions
Section titled “Exceptions”register() rejects rather than throwing synchronously.
| Exception | Condition |
|---|---|
InvalidStateError |
the registration has no active service worker yet. Awaiting navigator.serviceWorker.ready before calling register() avoids it (spec, “register(tag)” step 3). |
InvalidAccessError |
in Chromium, register() was called from a service worker that has no window client, or the tag exceeds the length limit. Chromium’s message is Attempted to register a sync event without a window or registration tag too long.. |
NotAllowedError |
the “Background sync” site permission is blocked. Chromium exposes it at chrome://settings/content/backgroundSync and in the per-site permission panel; the rejection message is Permission denied.. |
TypeError |
registration.sync is undefined in Firefox and Safari, so registration.sync.register() throws before any promise exists. Feature-detect with 'sync' in registration. |
A rejected waitUntil() promise is not an exception on the page: the browser schedules a retry (Chromium: up to three attempts, five minutes before the second, with a backoff factor of three) and sets lastChance to true on the final one.
Examples
Section titled “Examples”Both examples assume a registered service worker at /sw.js whose scope covers the page.
Queueing a failed POST and replaying it on sync
Section titled “Queueing a failed POST and replaying it on sync”The page writes the outgoing request to IndexedDB (here a minimal idb-keyval-style helper is assumed) and registers the tag; the worker drains the queue when the event fires. Keep the queue in storage, not in a worker variable: the browser may terminate the worker between the failed request and the sync event.
async function sendOrQueue(payload) { try { await fetch('/api/messages', { method: 'POST', body: JSON.stringify(payload) }); } catch { await outbox.add(payload); // IndexedDB-backed queue const registration = await navigator.serviceWorker.ready; await registration.sync.register('outbox'); }}
// sw.jsself.addEventListener('sync', (event) => { if (event.tag !== 'outbox') return; event.waitUntil(drainOutbox(event.lastChance));});
async function drainOutbox(lastChance) { for (const item of await outbox.all()) { const response = await fetch('/api/messages', { method: 'POST', body: JSON.stringify(item.payload) }); if (!response.ok && !lastChance) throw new Error(`replay failed: ${response.status}`); await outbox.remove(item.id); }}Throwing inside drainOutbox() rejects the waitUntil() promise, which is what asks the browser for a retry. On the lastChance pass the code above stops throwing and clears the queue so the registration ends; a production app would mark those items as failed and show them to the user on the next launch.
Detecting support and retrying without it
Section titled “Detecting support and retrying without it”Firefox and Safari expose no sync property on the registration. The fallback below retries once on the online event, which every browser fires, and otherwise leaves the item for the next page load.
async function deferOrRetry(tag, retryNow) { const registration = await navigator.serviceWorker.ready; if ('sync' in registration) { return registration.sync.register(tag); } // No Background Sync: retry as soon as the page sees the network return. window.addEventListener('online', () => retryNow(), { once: true });}The fallback only runs while the page is open; Background Sync can also run after it closes. Tell users when the fallback will send: “your message will send next time you open the app”.
See also
Section titled “See also”- Background Synchronization specification: register(tag) method (wicg.github.io)
- Introducing Background Sync (developer.chrome.com)
- Chromium source: sync_manager.cc (chromium.googlesource.com)
- Background Sync browser support
- Periodic Background Sync API
- Service worker lifecycle
- IndexedDB
Specifications
| Specification | Status |
|---|---|
| Background Sync | WICG draft |
- Legend
- Yes
- Partial
- Flag
- No
- Unknown
| Browser / Platform | Support | Versions | Confidence | Source | Notes |
|---|---|---|---|---|---|
| Chrome (Desktop)# | Yes | 49 | high | source | — |
| Chrome (Android)# | Yes | 49 | high | source | 1 |
| Edge (Desktop)# | Yes | 79 | high | source | 2 |
| Firefox (Desktop)# | No | — | high | source | 3 |
| Firefox (Android)# | No | — | high | source | 45 |
| Safari (macOS)# | No | — | high | source | 6 |
| Safari (iOS)# | No | — | high | source | 78 |
| Samsung Internet# | Yes | 5.0 | high | source | 9 |
| WebView (Android)# | No | — | high | source | 10 |
- Derived by browser-compat-data mirroring from Chrome.
- Derived by browser-compat-data mirroring from Chrome.
- No Firefox support is recorded in browser-compat-data.
- No Firefox for Android support is recorded in browser-compat-data.
- Derived by browser-compat-data mirroring from Firefox.
- Implementation tracking: https://webkit.org/b/182565.
- Implementation tracking: https://webkit.org/b/182565.
- Derived by browser-compat-data mirroring from Safari.
- Derived by browser-compat-data mirroring from Chrome Android.
- Implementation tracking: https://crbug.com/40449796.