# Advanced

> Production-grade capabilities (push, file access, platform integration) added as progressive enhancement with a compatibility check at every step.

Web Push, file access, background sync, and icon badges can enhance an app in browsers
that support them. Keep the page usable when a capability is unavailable. Write its fallback
before adding the enhancement, check for the feature, and check compatibility before shipping.
Complete [Getting started](/guides/getting-started/),
[Make it installable](/guides/installable/), and [Offline strategies](/guides/offline/) first;
these capabilities assume a registered service worker and an installable manifest.

## Write the capability gate once

Put the detection in one module so that the UI, the service worker, and analytics agree on
what is available. Detect support from the object graph without using the user agent. Keep buttons actionable
with a fallback for each capability.

```js
export const capabilities = {
  push: 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window,
  fileSystemAccess: 'showOpenFilePicker' in window,
  backgroundSync: 'serviceWorker' in navigator && 'SyncManager' in window,
  badging: 'setAppBadge' in navigator,
};

export const fallbacks = {
  push: () => showEmailDigestOptIn(),            // server-side digest instead of push
  fileSystemAccess: () => showDownloadAndUpload(), // <a download> plus <input type="file">
  backgroundSync: () => retryQueueOnNextLoad(),    // flush the IndexedDB queue on 'online'
  badging: () => showUnreadCountInTitle(),         // document.title = `(3) Field Notes`
};

export function withCapability(name, enhanced) {
  return capabilities[name] ? enhanced() : fallbacks[name]();
}
```

Presence of an API is a necessary condition, not proof the feature works for a given user:
`PushManager` exists on iOS Safari in a browser tab, yet WebKit grants push only to a web app
added to the Home Screen (iOS and iPadOS 16.4, 2023-03). Check the matching
compatibility entry when adding a gate, including the notes column.

## Add Web Push behind a user gesture

In web.dev's push overview, the client asks permission and subscribes. The server sends
the push, and the service worker receives it and shows a notification. The permission request must follow a gesture such as a click; WebKit states the
same for Home Screen web apps. Subscribe with your VAPID public key (web.dev: "the combination
of the private and public key is known as the application server keys"):

```js
async function enablePush(vapidPublicKey) {
  if (!capabilities.push) return fallbacks.push();
  const permission = await Notification.requestPermission();
  if (permission !== 'granted') return fallbacks.push();
  const registration = await navigator.serviceWorker.ready;
  const subscription = await registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: vapidPublicKey,
  });
  await fetch('/api/push/subscribe', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(subscription),
  });
}
```

The `endpoint` inside the subscription names the browser vendor's push service; web.dev
describes its domain as "essentially the push service" and its path as the client identifier.
Store the whole subscription object server-side and delete it when a send returns 404 or 410.
In the service worker, a `push` listener calls `self.registration.showNotification()`; a
handler that receives a push and shows nothing is treated as a silent push, which browsers do
not allow.

## Gate file access and background sync the same way

`showOpenFilePicker()` gives an editor read and write access to a user-chosen file; the
fallback is the pair every browser supports, `<input type="file">` for reading and an `<a
download>` for writing. Background Sync lets the worker replay writes made offline when
connectivity returns; the fallback is to keep the queue in IndexedDB and flush it on the
`online` event or the next page load. For each, call `withCapability()` to keep the two branches
together in the source, where you can check the fallback when changing the enhancement.

## Test the enhanced paths in DevTools

Chrome's **Service workers** pane has **Push** and **Sync** links that dispatch a `push` and a
`sync` event to the active worker without a server, which lets you exercise the receive side
before the backend exists. Use **Offline** to confirm that a queued write survives a reload and
is replayed when the box is unticked.

:::caution
The **Push data** field next to the **Push** link in Chrome DevTools defaults to the plain-text
payload `Test push message from DevTools`. The string `testPushMessageFromDevtools` and the `push-data` setting that
uses it are defined in the DevTools front end,
[`front_end/panels/application/ServiceWorkersView.ts`](https://github.com/ChromeDevTools/devtools-frontend/blob/main/front_end/panels/application/ServiceWorkersView.ts)
(main branch). A `push`
handler that parses `event.data.json()` throws on that payload because it is plain text. Read
`event.data.text()` first, or guard the JSON parse.
:::

## See also

- [Web Push](/reference/notifications/web-push/)
- [File System Access](/reference/capabilities/file-system-access/)
- [Background Sync](/reference/service-worker/background-sync/)
- [Badging](/reference/installation/badging/)
- [Compatibility by feature](/compatibility/by-feature/)
- [Push notifications overview](https://web.dev/articles/push-notifications-overview) (web.dev)
- [Web Push for Web Apps on iOS and iPadOS](https://webkit.org/blog/13878/web-push-for-web-apps-on-ios-and-ipados/) (webkit.org)

← Back to the [Guides](/guides/) overview.