# Periodic Background Sync API

> How to register and debug periodic background sync, handle retries and exceptions, and refresh in the foreground when support or permission is absent.

import Figure from '@components/Figure.astro';
import periodicSyncDiagram from '@assets/diagrams/periodic-background-sync.svg';

The `PeriodicSyncManager` interface registers named tasks that a browser can run in a service worker while the application is not in use. The application requests a minimum interval, but the browser chooses when to fire each `periodicsync` event. BCD `api.PeriodicSyncManager` records support from Chrome 80, Edge 80, and Samsung Internet 13, with no support recorded for Firefox or Safari.

<Figure src={periodicSyncDiagram} alt="Periodic background sync flow: an installed application gets its service worker registration, checks the periodic-background-sync permission, and registers a tag with a minimum interval. When the browser schedules the tag while online, it sends a periodicsync event to the service worker, which extends the event lifetime while it fetches and stores content." caption="Registration, browser scheduling, and event handling for periodic background sync." />

The API depends on service workers and is available only in a secure context. Chrome also requires the web app to be installed and launched as a distinct application. Chrome does not fire the event when its site engagement score is zero, requires a previously used network to be present, and adjusts frequency according to app use, power, and connectivity. A requested interval therefore specifies the minimum time between events.

## Syntax

```js
// Page or service worker
const registration = await navigator.serviceWorker.ready;
await registration.periodicSync.register(tag, { minInterval });
const tags = await registration.periodicSync.getTags();
await registration.periodicSync.unregister(tag);

// Service worker
self.addEventListener('periodicsync', (event) => {
  event.waitUntil(refresh(event.tag));
});
```

`ServiceWorkerRegistration.periodicSync` exposes the manager. `PeriodicSyncManager.register()` returns a `Promise<undefined>` that resolves when registration completes. Calling it again with the same tag updates that registration's `minInterval`; `getTags()` resolves with the active tags; and `unregister()` removes the matching registration, if present, before resolving with `undefined`.

The `periodicsync` event is delivered to `ServiceWorkerGlobalScope`. Its read-only `tag` is the string supplied to `register()`. The interface defines `tag` and does not define `lastChance`. Pass the promise for all asynchronous work to `event.waitUntil()` so the event lifetime covers that work.

## Parameters

| Name | Type | Description |
|---|---|---|
| `tag` | `string` | Identifies the registration and becomes `PeriodicSyncEvent.tag`. Periodic Background Sync and one-off Background Sync use separate tag namespaces. |
| `options` | `object` | Optional registration options. |
| `options.minInterval` | `number` | Suggested minimum milliseconds between events. The specification requires the actual interval to be at least this value. |

The browser also applies an effective minimum interval per origin. The specification permits this value to include a browser-defined amount based on engagement. Chrome documents that developers do not control the synchronization time and that its frequency follows app use while accounting for power and connectivity.

## Exceptions

`register()` rejects its promise when the specification's preconditions are not met.

| Exception | Condition |
|---|---|
| `InvalidStateError` (`DOMException`) | The service worker registration has no active worker. Await `navigator.serviceWorker.ready` before registering. |
| `NotAllowedError` (`DOMException`) | The `periodic-background-sync` permission is not `granted`. Query that permission before registering. |
| `InvalidAccessError` (`DOMException`) | The service worker clients for the registration's origin contain no client whose frame type is `top-level` or `auxiliary`. This check examines all clients for the registration's origin. |

When `registration.periodicSync` is absent, calling a method on it fails before `register()` can return a promise. Use `'periodicSync' in registration` to detect the property first, then install a foreground recovery path.

:::caution
Chrome DevTools can trigger a handler immediately from Application > Service Workers by entering a tag in the **Periodic Sync** field. This simulated event does not wait for the normal cadence. The separate **Periodic Background Sync** section starts lifecycle logging with **Start recording**, and Chrome keeps that recording enabled for up to three days. Use the first tool to inspect handler code and the second to inspect registration, sync, and unregistration activity ([Richer offline experiences with the Periodic Background Sync API](https://developer.chrome.com/docs/capabilities/periodic-background-sync), Chrome for Developers).
:::

## Examples

These examples use a page controlled by an active service worker at `/sw.js` and a `news-refresh` tag. The page code supplies a foreground refresh when periodic execution is unavailable.

### Registering with a foreground recovery path

Run this function from the page after service worker activation. It tests the manager before registering. The `try` and `catch` branches send a rejected registration to the same recovery path used when the property is absent. That path refreshes immediately and whenever the document becomes visible again.

```js
async function setUpRefresh(refreshNow) {
  const registration = await navigator.serviceWorker.ready;
  if ('periodicSync' in registration) {
    try {
      await registration.periodicSync.register('news-refresh', { minInterval: 24 * 60 * 60 * 1000 });
      return;
    } catch {
      // Rejected in a plain browser tab: fall through to the foreground fallback.
    }
  }
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') refreshNow();
  });
  refreshNow();
}
```

The fallback has a working route to fresh content, but it runs only while the page exists. Chrome's installed-app and engagement requirements still control whether a registered tag produces an event.

### Checking permission before registration

After feature detection confirms that `periodicSync` exists, call `permissions.query()` for the named permission. A state other than `granted` takes the visible notice path without calling `register()`.

```js
async function enableDailyRefresh() {
  const status = await navigator.permissions.query({ name: 'periodic-background-sync' });
  if (status.state !== 'granted') {
    showNotice('Install the app to get headlines refreshed in the background.');
    return;
  }
  const registration = await navigator.serviceWorker.ready;
  await registration.periodicSync.register('news-refresh', {
    minInterval: 24 * 60 * 60 * 1000,
  });
}
```

Chrome exposes periodic background sync only after installation and launch as a distinct application. The notice gives a user in a regular tab a concrete next action, while the preceding example supplies the foreground refresh route.

### Handling a failed network response

Put the event listener in the service worker. This handler checks the HTTP status before replacing the cached response. A non-success status throws, which rejects the promise passed to `waitUntil()`.

```js
self.addEventListener('periodicsync', (event) => {
  if (event.tag !== 'news-refresh') return;
  event.waitUntil((async () => {
    const response = await fetch('/api/headlines', { cache: 'no-store' });
    if (!response.ok) throw new Error(`headlines: ${response.status}`);
    const cache = await caches.open('news');
    await cache.put('/api/headlines', response);
  })());
});
```

The specification permits a user agent to retry after a rejected `waitUntil()` promise. The algorithm stops when the retry count is greater than the configured maximum; otherwise it increments the count, waits using back-off, and retries. Because the retry count starts at zero, the specification's default maximum of zero permits one retry after the initial failure. A user agent may also impose stricter execution and lifetime-extension limits on `PeriodicSyncEvent`, especially on retries. The algorithm returns the registration to `pending` after success, after the retry limit, or after re-registration while firing.

### Confirming the tag and testing the handler

Use `getTags()` in the page to confirm that the browser holds the expected registration. If the tag is absent, the code switches to the same foreground route instead of reporting background refresh as enabled.

```js
async function verifyNewsRefresh(refreshNow) {
  const registration = await navigator.serviceWorker.ready;
  if (!('periodicSync' in registration)) {
    await refreshNow();
    return { registered: false, reason: 'unsupported' };
  }

  const tags = await registration.periodicSync.getTags();
  if (!tags.includes('news-refresh')) {
    await refreshNow();
    return { registered: false, reason: 'tag-missing' };
  }

  return { registered: true, reason: null };
}
```

For an immediate handler check in Chrome DevTools, open Application > Service Workers, enter `news-refresh` in **Periodic Sync**, and press the adjacent button. The expected observation is a request to `/api/headlines` from the handler. Inspect its HTTP status and the `news` cache entry; DevTools firing the event does not demonstrate that Chrome's installation, engagement, network, or scheduling conditions will fire it later. If no request appears, confirm that DevTools is inspecting the service worker registration that controls the page and that the listener's tag matches the entered text.

Call `registration.periodicSync.unregister('news-refresh')` when the user disables background updates. `getTags()` then provides the registration state that the settings UI can display.

## Correction (2026-11-18)

- Corrected failure handling: a rejected `waitUntil()` promise may be retried after a back-off up to the user agent's configured limit. Execution and lifetime-extension limits are optional user-agent constraints; the cited sources do not say that Chrome necessarily terminates the worker or interrupts a cache write.
- Corrected registration prerequisites: `InvalidAccessError` depends on the clients for the registration's origin, not the frame that calls `register()`. Removed unsupported claims that the app must first open on a previously unused network and that Firefox or Safari throws `TypeError` when querying the permission.

## See also

- [Web Periodic Background Synchronization: `register()`](https://wicg.github.io/periodic-background-sync/#dom-periodicsyncmanager-register) (WICG)
- [Richer offline experiences with the Periodic Background Sync API](https://developer.chrome.com/docs/capabilities/periodic-background-sync) (Chrome for Developers)
- [Periodic Background Sync browser support](/compatibility/periodic-background-sync/)
- [Background Sync API](/reference/service-worker/background-sync/)
- [Periodic background sync for content updates](/reference/notifications/periodic-background-sync/)
- [Service worker lifecycle](/reference/service-worker/lifecycle/)