# Periodic Background Sync API

The Periodic Background Sync API allows web applications to alert their service worker to update content at a periodic interval, even when the application is closed. This ensures that when the user opens the app, the content is already fresh (e.g., latest news articles).

## 1. The Concept

Unlike the standard Background Sync API which is for "one-off" retries (like sending a message), Periodic Background Sync is for recurring tasks.

**Constraints:**
*   **Installed PWA:** Most browsers only allow this for installed Progressive Web Apps.
*   **Engagement:** The frequency of syncs often depends on a "site engagement score". If the user rarely visits, syncs happen less often.
*   **Battery/Network:** The browser may delay syncs to save battery or wait for Wi-Fi.

## 2. Permissions

You must query the permission status before registering.

```javascript
async function checkPermission() {
  const status = await navigator.permissions.query({
    name: 'periodic-background-sync',
  });

  if (status.state === 'granted') {
    // Permission granted
    return true;
  } else {
    console.log('Periodic Background Sync permission denied.');
    return false;
  }
}
```

## 3. Registering a Periodic Sync

You register the sync from the main page context using the `ServiceWorkerRegistration`.

```javascript
async function registerPeriodicSync() {
  const registration = await navigator.serviceWorker.ready;
  
  if ('periodicSync' in registration) {
    try {
      // Register a sync with a minimum interval of 1 day (in milliseconds)
      await registration.periodicSync.register('get-daily-news', {
        minInterval: 24 * 60 * 60 * 1000,
      });
      console.log('Periodic sync registered!');
    } catch (error) {
      console.error('Periodic sync registration failed:', error);
    }
  }
}
```

## 4. Handling the Event

The Service Worker listens for the `periodicsync` event.

```javascript
// service-worker.js
self.addEventListener('periodicsync', (event) => {
  if (event.tag === 'get-daily-news') {
    event.waitUntil(fetchAndCacheNews());
  }
});

async function fetchAndCacheNews() {
  const cache = await caches.open('news-cache');
  const response = await fetch('/api/news/latest');
  await cache.put('/api/news/latest', response);
}
```

## 5. Unregistering

You can stop the periodic sync if it's no longer needed.

```javascript
async function unregisterPeriodicSync() {
  const registration = await navigator.serviceWorker.ready;
  if ('periodicSync' in registration) {
    await registration.periodicSync.unregister('get-daily-news');
  }
}
```

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/service-workers-and-pwa]]
[[programming/javascript/vanilla/background-sync-api]]