# OpenPWA — full text > Full plain-text bodies of every reference, guide, and ecosystem entry, for LLM > ingestion. Compatibility datasets are linked to their JSON exports below. > Source: https://openpwa.net/llms.txt --- # Reference URL: https://openpwa.net/reference/ > The PWA knowledge tree (manifest, service workers, installability, device capabilities, storage, notifications, performance, and platforms), kept current and source-backed. import { CardGrid, LinkCard } from '@astrojs/starlight/components'; Progressive Web Apps use web app manifests together with service workers and browser APIs for installation and offline use. These technologies also provide storage and notifications, plus device capabilities. Look up their behaviour and platform differences in eight sections, with entries at `/reference/
/`. For machine-readable content, use the `.md` version or the structured **TechArticle + Dataset** metadata. --- # Capabilities URL: https://openpwa.net/reference/capabilities/ > Device and platform capabilities: File System, Web Share, Bluetooth, WebGPU, Payment, and more. import { CardGrid, LinkCard } from '@astrojs/starlight/components'; Device and platform APIs let a PWA read and write local files, share content, access hardware, accelerate graphics, and take payments, as native apps do. Most require a secure context, a user gesture, and explicit permission. Support differs across browser engines. ## In this section ← Back to the [Reference](/reference/) overview. --- # Barcode Detection API (Shape Detection) URL: https://openpwa.net/reference/capabilities/barcode-detection/ > BarcodeDetector detects supported linear and two-dimensional barcodes in image sources. This reference covers formats, results, input errors, and fallbacks. The Barcode Detection API detects linear and two-dimensional barcodes in image sources. `BarcodeDetector.detect()` returns a promise containing `DetectedBarcode` values with the decoded `rawValue` and format. Results also expose a bounding box and corner points. BCD records full support from Chrome for Android 83. Desktop Chromium support is platform-limited, Safari 17 exposes the interface behind the Shape Detection API preference, and Firefox is recorded as unsupported (BCD `api.BarcodeDetector`). ## Syntax ```js new BarcodeDetector() new BarcodeDetector(options) BarcodeDetector.getSupportedFormats() detector.detect(image) ``` The secure-context interface is exposed in windows and workers. `getSupportedFormats()` fulfills with the format names the user agent understands, while `detect()` fulfills with detected barcodes in the supplied image. ## Parameters The constructor accepts one optional member. | Member | Type | Meaning | |---|---|---| | `formats` | `string[]` | Limit later detections to the named barcode formats. If omitted, the user agent should search all supported formats. | `detect(image)` accepts an `HTMLImageElement`, `SVGImageElement`, `HTMLVideoElement`, `HTMLCanvasElement`, `ImageBitmap`, or `OffscreenCanvas`. It also accepts a `VideoFrame` or image `Blob`, plus `ImageData`. Each result has `boundingBox` and `cornerPoints`, plus `format` and `rawValue`. ## Exceptions The constructor throws `TypeError` when `formats` is empty or contains `"unknown"`. The [`detect()` algorithm](https://wicg.github.io/shape-detection-api/#image-sources-for-detection) (WICG) defines these failures. | Exception | Condition | |---|---| | `TypeError` | No image is supplied, or its type is not an accepted image source. | | `SecurityError` | The image has a different effective script origin, or a canvas is not origin-clean. | | `InvalidStateError` | An `HTMLImageElement` is broken or not fully decoded, or a video's `readyState` is `HAVE_NOTHING` or `HAVE_METADATA`. | :::caution BCD records partial desktop support. Chrome 88 supports ChromeOS and macOS. Edge 83 and Opera 69 list macOS only. It also records that the interface silently failed before Chrome 113 on macOS Ventura 13 and later ([BCD `api.BarcodeDetector`](https://raw.githubusercontent.com/mdn/browser-compat-data/main/api/BarcodeDetector.json), MDN browser-compat-data). ::: ## Examples Detect the constructor before creating it. A manual text field is a usable fallback when native barcode detection is absent. ### Scanning an image selected from disk This snippet creates an image picker, a manual entry field, and an output element. Supported browsers scan the selected image `Blob`; other browsers leave the manual field enabled. ```js const picker = document.body.appendChild(document.createElement("input")); const manual = document.body.appendChild(document.createElement("input")); const output = document.body.appendChild(document.createElement("p")); picker.type = "file"; picker.accept = "image/*"; manual.placeholder = "Enter the barcode value"; if (!("BarcodeDetector" in globalThis)) { picker.disabled = true; output.textContent = "Automatic scanning is unavailable; enter the value manually."; } else { const detector = new BarcodeDetector(); picker.addEventListener("change", async () => { const [file] = picker.files; if (!file) return; const codes = await detector.detect(file); output.textContent = codes[0]?.rawValue ?? "No barcode detected"; }); } ``` The fallback remains in the document even when the detector exists, so an empty detection result does not block manual entry. ### Requesting a format the platform supports Check the user agent's format list before constructing a QR-code detector. Return `null` when either the interface or format is unavailable. ```js async function createQrDetector() { if (!("BarcodeDetector" in globalThis)) return null; const formats = await BarcodeDetector.getSupportedFormats(); if (!formats.includes("qr_code")) return null; return new BarcodeDetector({ formats: ["qr_code"] }); } const detector = await createQrDetector(); if (!detector) console.info("Use the manual code field"); ``` The caller can retain manual entry whenever the function returns `null`. ## See also - [Screen Capture API](/reference/capabilities/screen-capture/), for obtaining frames from a display capture - [Generic Sensor API](/reference/capabilities/sensors/), another secure-context device API - [Accelerated Shape Detection in Images](https://wicg.github.io/shape-detection-api/#barcode-detection-api) (wicg.github.io) - [Barcode Detection API](https://developer.mozilla.org/en-US/docs/Web/API/Barcode_Detection_API) (MDN) --- # Shipped, origin trial, flag, in development URL: https://openpwa.net/reference/capabilities/capability-status/ > What shipped, origin trial, flag, and in development mean in Chromium's launch process, where each status is recorded, and how to gate code on the capability. A capability status is a claim about how far a feature has travelled through one engine's release process, in one set of builds. In development, behind a flag, in an origin trial, and shipped describe release stages and enabling mechanisms. Runtime capability detection determines whether a visitor's browser exposes the feature. ## How it works The labels are not marketing terms. They map onto named stages in the public processes each engine runs, and each stage has a record a developer can read. ### The stages in Chromium's launch process Chromium's launching-features document sets out the path. A ChromeStatus entry is step 0 for a web-exposed feature. At the prototyping step, the owner sends an Intent to Prototype to blink-dev and starts landing code, and the document states that any changes landing at this stage are behind a feature flag. Once the implementation is functional and reasonably complete as a runtime enabled feature, the document recommends, but does not require, proceeding to the Dev Trials stage and sending a Ready for Developer Testing email. An origin trial is an optional later step after the flag stage. The document describes proceeding to the Origin Trial stage, generating an Intent to Experiment mail to blink-dev, and starting the trial after at least one LGTM from the API owners. Shipping is the separate gate: the document names three LGTMs from API owners on an Intent to Ship. Trials are time-boxed. An initial origin trial or experiment may only run for 12 milestones of Chromium. Each extension may only be for 6 milestones at a time and requires demonstrated progress on a draft spec, TAG review, signals requests, community outreach, and web-platform-tests. ### What an origin trial actually turns on Chrome's origin trials guide describes the enabling mechanism. Registering a trial enables a feature for all users on the registered origin. They do not need to toggle flags or switch to an alternative build, though they may need to upgrade. The token travels either as a `` tag in the ``, as an `Origin-Trial` HTTP response header, or injected programmatically. The framework takes the first valid token and ignores the rest. Chrome ignores invalid or expired tokens. The guide also describes variants of origin trials. A deprecation trial, sometimes called a reverse origin trial, temporarily re-enables a feature that has been removed; the guide gives mutation events, removed starting in Chrome 127, as its example. A third-party origin trial lets a provider of embedded content use the feature across multiple sites without a separate token for each origin. ## Where it is supported Firefox records the flag stage as a preference. MDN's experimental features page lists, per feature, the builds it is included in (Nightly, Beta, Developer Edition, or Release), whether it is activated by default, and the name of the `about:config` preference that enables it. Features usually appear first in Nightly and are often enabled by default there for early feedback. If no major problems are found, they reach Beta and Developer Edition. Approved features ship in the stable Release channel; once a feature is enabled by default in a release, MDN removes it from the experimental features page. WebKit's feature status page says it has been retired. It points readers to MDN or Can I Use for support data and to WebKit Standards Positions for the project's positions on emerging specifications. ## Mapping a status to a support decision The practical translation is narrow. A feature flag lets a developer enable a capability in a build that includes it. An origin trial lets a registered origin enable a capability for its visitors without asking each visitor to toggle a flag or use an alternative build. Chromium's process puts changes landed during prototyping behind a feature flag; its next stage is named "Feature Complete behind a flag and implementation refinement." Those states are not something a page can read. A status board is a planning input for deciding whether to write the code path at all. The final runtime result still depends on the capability exposed by the visitor's browser, whether it comes from an enabled flag, a valid origin-trial token, or a default release, so the code path has to test the capability itself. :::caution A status label and a standards position are different records. At the Dev Trials stage, Chromium's launch process says to consider requesting signals from other browser vendors and the developer community. Before shipping, it says to request signals at least one month in advance if they have not already been obtained. The WebKit standards-positions issue for the Web Install API carries the label `position: oppose` ([Web Install API](https://github.com/WebKit/standards-positions/issues/463), WebKit). ::: ## Examples Runtime detection can test both the presence of a method and whether a specific payload passes that method's validation. The first example provides a fallback when Web Share is absent; the second checks a selected file without starting a share request. ### Gating on the capability at runtime The test checks the method the feature exposes. MDN documents `navigator.share()` as requiring a secure context and transient activation, so the call is made from the button handler ([Navigator: share() method](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share), MDN). ```html Capability detection

``` The branch tests the capability when the user acts. The fallback changes the page visibly and provides a usable link without calling another optional API. ### Checking a file payload before offering an action `navigator.canShare()` returns whether specified data can be shared with `navigator.share()`. Pass the selected `File` in the `files` array to test that payload ([Navigator: canShare() method](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/canShare), MDN). ```html File share capability

No file selected.

``` The example reports only the synchronous validation result. It does not open the share sheet or claim that a share completed. ## See also - [Launching features in Blink](https://www.chromium.org/blink/launching-features/) (chromium.org) - [Get started with origin trials](https://developer.chrome.com/docs/web-platform/origin-trials) (developer.chrome.com) - [Experimental features in Firefox](https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Experimental_features) (developer.mozilla.org) - [WebKit Feature Status](https://webkit.org/status/) (webkit.org) - [Web Install API (navigator.install)](/reference/installation/navigator-install/) - [Installability criteria](/reference/installation/installability-criteria/) - [Web Share API](/reference/capabilities/web-share/) --- # Async Clipboard API URL: https://openpwa.net/reference/capabilities/clipboard/ > navigator.clipboard read(), readText(), write(), and writeText(), ClipboardItem members, every DOMException the spec defines, and copy and paste fallbacks. The Async Clipboard API (`navigator.clipboard`) reads and writes the system clipboard through promises. It replaces `document.execCommand('copy')` and `('paste')`. Use `writeText()` and `readText()` for text. For images, HTML, and multi-format payloads, pass `ClipboardItem` objects through `write()` and `read()`. Chrome 66 shipped `writeText()` and `readText()`, and Chrome 76 added `read()`, `write()`, and `ClipboardItem`; Edge 79 and Samsung Internet 12.0 follow Chromium. Firefox added `writeText()` in 63, `readText()` in 125, and `read()`, `write()`, and `ClipboardItem` in 127. Safari 13.1 on macOS and 13.4 on iOS shipped all four methods at once (BCD `api.Clipboard`). The API exists only in a `Window` on a secure context: on `http://` origins other than `localhost`, `navigator.clipboard` is `undefined`, and Chromium rejects reads from workers with `NotAllowedError`. ## Syntax ```js navigator.clipboard.readText() navigator.clipboard.read() navigator.clipboard.read(formats) navigator.clipboard.writeText(data) navigator.clipboard.write(data) new ClipboardItem(items) new ClipboardItem(items, options) clipboardItem.getType(type) ClipboardItem.supports(type) ``` `readText()` returns `Promise`; `read()` returns `Promise>` whose items carry type names only, with the bytes fetched when `getType()` is called; `writeText()` and `write()` return `Promise`. Reads need transient user activation in Firefox 125+ and Safari 13.1+, and either activation or the `clipboard-read` permission in Chrome. Writes need transient activation in Firefox 63+ and Safari 13.1+, and since Chrome 107 either activation or the `clipboard-write` permission (before 107 the permission alone decided). `ClipboardItem.supports()` is static and synchronous; it exists in Chrome 121, Firefox 127, and Safari 18.4. ## Parameters The three method arguments and the two `ClipboardItem` constructor arguments cover every input the specification defines. | Parameter | Type | Required | Description | |---|---|---|---| | `data` (`writeText`) | `DOMString` | Yes | Written as a `text/plain;charset=utf-8` blob. On Windows the browser replaces `\n` with `\r\n` first. | | `data` (`write`) | `sequence` | Yes | Chrome 76+ and Firefox 127+ accept exactly one item; an array with two or more items rejects with `NotAllowedError` (BCD `api.Clipboard.write`). | | `formats` (`read`) | `ClipboardUnsanitizedFormats` | No | One member, `unsanitized: sequence`, asking for raw rather than sanitized bytes. Chrome 122 honours it for `text/html` only; any other type rejects. | | `items` (constructor) | `record` | Yes | MIME type to `Promise` (a plain `Blob` or string is wrapped). Keys prefixed with `"web "` are custom formats (Chrome 104). | | `options.presentationStyle` | `"unspecified"`, `"inline"`, or `"attachment"` | No | Default `"unspecified"`; a hint to paste targets. Chrome ignores it; Firefox 127 and Safari 13.1 expose it on read items. | | `type` (`getType`, `supports`) | `DOMString` | Yes | A MIME type, optionally with the `"web "` prefix. | A `ClipboardItem` exposes `types` (a frozen array of its MIME type strings) and `presentationStyle`. The mandatory types every browser must accept are `text/plain`, `text/html`, and `image/png`; `image/svg+xml` is optional and ships in Chrome 124. ## Exceptions Methods report failures by rejecting their promises. The `ClipboardItem` constructor and the synchronous part of `getType()` throw exceptions. | Exception | Condition | |---|---| | `NotAllowedError` | `read()` or `readText()` when "check clipboard read permission" fails (no transient activation and no granted `clipboard-read`); `write()` or `writeText()` when the write check fails; a blob whose type is outside the mandatory and optional types; sanitization that did not complete; a representation promise that rejected; `read(formats)` naming an `unsanitized` type outside the optional unsanitized list; more than one `ClipboardItem` in Chrome and Firefox; the document not having focus in Chromium; a `clipboard-read` or `clipboard-write` Permissions Policy denial. | | `NotFoundError` | `readText()` when the clipboard holds no `text/plain` representation, or decoding that representation fails. | | `TypeError` | `new ClipboardItem()` with an empty `items` record, a key that does not parse as a MIME type, or the same type listed twice; `getType()` with an unparsable `type`. | | `InvalidStateError` | `getType()` on an item from `read()` after the system clipboard changed, or on an item whose originating system entry is gone. | | `DataError` | Chromium only: a `ClipboardItemData` promise that could not be read or decoded, or clipboard contents that changed while a paste event was being handled. | Firefox adds a browser-level gate the specification does not name: `read()` and `readText()` show a paste prompt the user must accept, suppressed only when the clipboard content is same-origin (BCD `api.Clipboard.read`). A declined prompt rejects with `NotAllowedError`. :::caution Chromium's [`clipboard_promise.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/clipboard/clipboard_promise.cc) defines three rejections as `NotAllowedError`. A call made while the document does not have focus rejects with `Document is not focused.`, a `readText()` or `read()` call whose permission status is not granted rejects with `Read permission denied.`, and `write()` with more than one `ClipboardItem` rejects with `Support for multiple ClipboardItems is not implemented.` ::: ## Examples Check that the method you need exists and provide a fallback when it does not. Run writes from a `click` handler while transient activation is valid. ### Copying text with a hidden-textarea fallback `navigator.clipboard.writeText()` covers Chrome 66+, Firefox 63+, and Safari 13.1+; everything older, and any `http://` page, needs the deprecated `document.execCommand('copy')`, which still works in those engines for plain text only. ```js async function copyText(text) { if (navigator.clipboard?.writeText) { await navigator.clipboard.writeText(text); return 'async'; } const area = document.createElement('textarea'); area.value = text; area.setAttribute('readonly', ''); area.style.position = 'fixed'; area.style.opacity = '0'; document.body.append(area); area.select(); const ok = document.execCommand('copy'); area.remove(); return ok ? 'legacy' : 'failed'; } document.querySelector('#copy').addEventListener('click', async () => { const result = await copyText(location.href); console.log(`copied via ${result}`); }); ``` The function returns which path ran so the UI can say "Copied" only when one of them succeeded; `execCommand` returns `false` instead of rejecting when the browser refuses. ### Writing a PNG and an HTML fallback in one item A single `ClipboardItem` can carry several representations; the paste target picks the richest one it understands. Check `ClipboardItem.supports()` where it exists (Chrome 121, Firefox 127, Safari 18.4) and treat its absence as "mandatory types only". ```js async function copyChart(canvas, captionHtml) { if (!navigator.clipboard?.write || !('ClipboardItem' in window)) { return copyText(captionHtml.replace(/<[^>]+>/g, '')); } const png = new Promise((resolve) => canvas.toBlob(resolve, 'image/png')); const items = { 'image/png': png }; const htmlOk = typeof ClipboardItem.supports !== 'function' || ClipboardItem.supports('text/html'); if (htmlOk) { items['text/html'] = new Blob([captionHtml], { type: 'text/html' }); } try { await navigator.clipboard.write([new ClipboardItem(items)]); } catch (err) { if (err.name !== 'NotAllowedError') throw err; return copyText(captionHtml.replace(/<[^>]+>/g, '')); } } ``` Pass the `toBlob` promise directly so the browser can start writing during the gesture and fill in the bytes later. Awaiting it first loses that ordering, which Safari 13.1 requires (web.dev, Unblocking clipboard access). ### Reading an image from the clipboard without a Chromium-only permission query Only Chromium recognises `clipboard-read` as a Permissions API name; `navigator.permissions.query({ name: 'clipboard-read' })` throws `TypeError` in Firefox and Safari. Skip the query, call `read()` inside the gesture, and branch on the rejection. ```js document.querySelector('#paste').addEventListener('click', async () => { if (!navigator.clipboard?.read) { document.querySelector('#paste-area').focus(); // let the user press Ctrl+V / Cmd+V return; } try { const items = await navigator.clipboard.read(); const item = items.find((i) => i.types.includes('image/png')); if (!item) { console.log('no PNG on the clipboard; types were', items.flatMap((i) => i.types)); return; } const blob = await item.getType('image/png'); document.querySelector('#preview').src = URL.createObjectURL(blob); } catch (err) { if (err.name === 'NotAllowedError') { document.querySelector('#paste-area').focus(); return; } throw err; } }); ``` Focusing a contenteditable or textarea and listening for the `paste` event is the portable fallback: the `paste` event's `clipboardData.files` delivers the same PNG in every engine without any permission. ## See also - [Web Share API](/reference/capabilities/web-share/), where a clipboard write is the usual fallback - [File System Access API](/reference/capabilities/file-system-access/), for files too large to round-trip through the clipboard - [Clipboard API and events: write() method](https://www.w3.org/TR/clipboard-apis/#dom-clipboard-write) (w3.org) - [Unblocking clipboard access](https://web.dev/articles/async-clipboard) (web.dev) - [Async Clipboard API](https://webkit.org/blog/10855/async-clipboard-api/) (webkit.org) - [Chrome Platform Status: Asynchronous Clipboard API](https://chromestatus.com/feature/5861289330999296) (chromestatus.com) --- # ClipboardItem URL: https://openpwa.net/reference/capabilities/clipboard-item/ > ClipboardItem packages one clipboard payload in one or more MIME representations; its API includes types, getType(), and supports(). The `ClipboardItem` interface packages clipboard data as one or more MIME representations. Pass an item to `navigator.clipboard.write()`, or receive items from `navigator.clipboard.read()`, then inspect `types` and retrieve a representation with `getType()` ([Clipboard API and events](https://www.w3.org/TR/clipboard-apis/#clipboarditem), W3C). `ClipboardItem` is available in secure contexts. BCD `api.ClipboardItem` records the interface from Chrome 76, Chrome for Android 84, Firefox 127, and Safari 13.1. The [Async Clipboard compatibility data](/compatibility/clipboard/) shows the related read and write surface. MDN marks `ClipboardItem` as Baseline 2024 while noting that individual parts have different support ([ClipboardItem](https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem), MDN). ## Syntax ```js const item = new ClipboardItem(items); const styledItem = new ClipboardItem(items, options); item.types; item.presentationStyle; await item.getType(type); ClipboardItem.supports(type); ``` The constructor accepts a record whose keys are MIME types and whose values are strings, `Blob` objects, or promises for either form. The specification exposes `ClipboardItem` on `Window`, not workers. An item returned by `navigator.clipboard.read()` lists formats in `types`; the specification fetches the bytes when `getType()` runs and shares an in-flight read between concurrent calls for the same type. ## Members | Member | Type | Meaning | |---|---|---| | `options.presentationStyle` | `"unspecified"`, `"inline"`, or `"attachment"` | Optional presentation hint; the default is `"unspecified"`. | | `types` | Frozen array of strings | MIME types represented by the item. | | `presentationStyle` | String | The presentation hint stored on the item. | | `getType(type)` | `Promise` | Retrieves the blob for a represented MIME type. | | `supports(type)` | Boolean | Reports whether the browser supports a MIME type for clipboard writing. | The specification distinguishes a constructed item from an item returned by `read()`. Constructed values already hold the supplied representation promises. A read item acts as a lazy fetcher: its `types` reflect the formats present when `read()` ran, while `getType()` requests the selected payload. If the system clipboard changes before that request, the specification rejects the call with `InvalidStateError`. `ClipboardItem.supports()` is synchronous. Use it to decide whether to add an optional representation, but still keep a representation that the receiving application can use. MDN documents `types` and `presentationStyle` as read-only properties and `getType()` as the method that returns the requested representation as a blob ([ClipboardItem](https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem), MDN). `presentationStyle` supplies a presentation hint to the paste destination. The specification defines `"unspecified"`, `"inline"`, and `"attachment"`, with `"unspecified"` as the default. The hint does not replace format selection: a reader still chooses a representation from `types`. `supports(type)` serves a different purpose. The specification returns `true` when the type is among its mandatory or optional data types and returns `false` otherwise ([Clipboard API and events](https://www.w3.org/TR/clipboard-apis/#clipboarditem), W3C). For a text-only task, MDN recommends the convenience methods `readText()` and `writeText()` instead of the general `read()` and `write()` methods. `ClipboardItem` is the form used when `read()` or `write()` carries strings or arbitrary data represented by `Blob` objects. Its constructor accepts one or more MIME type keys and the corresponding data values, so one item can make separate representations available to the receiving application ([ClipboardItem](https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem), MDN). The constructor preserves the record's representation order in `types`. WebKit documents why that order matters on macOS and iOS: it writes types to the system pasteboard in the supplied order, and native applications may treat earlier types as higher-fidelity choices ([Async Clipboard API](https://webkit.org/blog/10855/async-clipboard-api/), WebKit). Put the representation that best preserves the copied content first, followed by formats that more paste targets can consume. A rich-text item can therefore list `text/html` before `text/plain` while still giving a plain-text editor usable data. Each value may defer work with a promise. The web.dev clipboard article recommends starting asynchronous preparation inside the promise supplied to `ClipboardItem` for Safari, instead of awaiting the preparation before constructing the item ([Unblocking clipboard access](https://web.dev/articles/async-clipboard), web.dev). This keeps the `write()` call in the user-activation handler while the representation finishes. The promise must still resolve to a string or `Blob` accepted by the constructor; a rejected representation promise makes the clipboard write fail under the specification's write algorithm. The constructor also normalizes MIME type keys before storing them. The specification throws `TypeError` for an empty `items` record, a key that cannot be parsed as a MIME type, or a duplicate representation with the same parsed type and custom-format flag. A standard `text/html` representation and a `web text/html` custom representation do not collide because the latter retains its custom flag. These checks happen when the item is constructed, before it is passed to `navigator.clipboard.write()` ([Clipboard API and events](https://www.w3.org/TR/clipboard-apis/#clipboarditem), W3C). ## Exceptions The constructor validates the representation record and MIME type strings. The Clipboard specification requires `getType()` to throw `TypeError` when its argument cannot be parsed as a MIME type. When the type is valid but the item has no matching representation, the returned promise rejects with `NotFoundError`. The specification also defines `InvalidStateError` for a read item whose source clipboard has changed ([Clipboard API and events](https://www.w3.org/TR/clipboard-apis/#clipboarditem), W3C). :::caution Calling `getType()` with a valid type that the item does not represent does not choose a substitute: the returned promise rejects with `NotFoundError`. Chromium reports this case as `The type was not found` in its [`ClipboardItem` implementation](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/clipboard/clipboard_item.cc). An argument that cannot be parsed as a MIME type throws `TypeError`. Read `item.types` first, then provide a text or UI fallback when the requested representation is missing ([Clipboard API and events](https://www.w3.org/TR/clipboard-apis/#clipboarditem), W3C). ::: ## Examples The examples use a click handler because clipboard writes are permission-sensitive. Each branch updates visible status text so the reader can tell whether the rich or fallback path ran. ### Writing HTML with a plain-text representation Package HTML and plain text in the same item. If the rich clipboard surface is absent, use `writeText()`; if that method is also absent, select a textarea and ask `execCommand("copy")` to copy plain text. ```html ClipboardItem example ``` The web.dev clipboard article documents `execCommand()` as the older DOM-bound route and shows multiple MIME representations in one `ClipboardItem` ([Unblocking clipboard access](https://web.dev/articles/async-clipboard), web.dev). The fallback above preserves the plain-text task without claiming rich-format support. ### Reading an image and handling a missing representation Check the API and the item's advertised types before requesting bytes. This failure path focuses a paste target when direct clipboard reading is unavailable, denied, or contains no PNG. ```html Paste a PNG
Paste the image here when prompted.
``` The W3C algorithm defines lazy retrieval for items returned by `read()`. The code requests only the advertised `image/png` representation and leaves a concrete manual-paste route for the other branches. ## See also - [Async Clipboard API](/reference/capabilities/clipboard/) - [Web Share API](/reference/capabilities/web-share/) - [Clipboard API and events: ClipboardItem interface](https://www.w3.org/TR/clipboard-apis/#clipboarditem) (w3.org) - [ClipboardItem](https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem) (MDN) - [Unblocking clipboard access](https://web.dev/articles/async-clipboard) (web.dev) --- # Compute Pressure API URL: https://openpwa.net/reference/capabilities/compute-pressure/ > PressureObserver reports system-resource pressure changes. This reference covers records, sampling, policy errors, cleanup, and an unsupported-browser fallback. The Compute Pressure API reports high-level pressure changes for system resources such as the CPU. A `PressureObserver` delivers `PressureRecord` objects to a callback after `observe()` starts watching a source. ## Where it is supported BCD records `PressureObserver` from desktop Chrome 125 and mirrors that support to Edge. Chrome for Android is recorded as unsupported. Firefox and Safari are also recorded as unsupported (BCD `api.PressureObserver`). ## Syntax ```js const observer = new PressureObserver(callback) observer.observe(source) observer.observe(source, options) observer.unobserve(source) observer.disconnect() observer.takeRecords() ``` The interface is available in secure-context windows plus dedicated and shared workers, but not service workers. `observe()` returns a promise that fulfills with `undefined` after observation begins. ## Parameters The constructor receives a callback. The callback receives an array of records collected since its previous invocation or the previous `takeRecords()` call, plus the observer itself. | Parameter or member | Type | Meaning | |---|---|---| | `source` | `string` | The pressure source to observe. Use `PressureObserver.knownSources` as a hint for sources the user agent knows. | | `options.sampleInterval` | `number` | Requested minimum interval between callbacks, in milliseconds. The default is `0`. | | `PressureRecord.source` | `string` | Source represented by the record. | | `PressureRecord.state` | `string` | High-level pressure state. | | `PressureRecord.time` | `DOMHighResTimeStamp` | Timestamp for the record. | `unobserve(source)` stops one source. `disconnect()` stops every source and clears queued records; `takeRecords()` returns queued records and empties that queue. ## Exceptions [`observe()`](https://w3c.github.io/compute-pressure/#dom-pressureobserver-observe) can report policy and source failures. | Exception | Condition | |---|---| | `TypeError` | `observe()` receives a source that is not a value in the `PressureSource` enum. | | `NotAllowedError` | The `compute-pressure` Permissions Policy disallows the API. | | `NotSupportedError` | `observe()` receives a source the user agent does not support. | :::caution The `compute-pressure` Permissions Policy has a default allowlist of `self`. When an owning document is not allowed to use that policy-controlled feature, the Compute Pressure specification requires `observe()` to return a promise rejected with `NotAllowedError` ([`PressureObserver.observe()` method steps](https://w3c.github.io/compute-pressure/#dom-pressureobserver-observe), Compute Pressure Level 1). ::: ## Examples Detect `PressureObserver` before constructing it and retain a fixed workload mode when observation is unavailable. ### Reducing work when CPU pressure rises This snippet writes the reported state into the document and switches a workload label for `serious` or `critical` records. The fallback keeps the reduced mode. ```js const status = document.body.appendChild(document.createElement("p")); const mode = document.body.appendChild(document.createElement("p")); if (!("PressureObserver" in globalThis)) { status.textContent = "Compute pressure is unavailable."; mode.textContent = "Reduced workload"; } else { const observer = new PressureObserver((records) => { const latest = records.at(-1); status.textContent = `CPU pressure: ${latest.state}`; mode.textContent = ["serious", "critical"].includes(latest.state) ? "Reduced workload" : "Full workload"; }); observer.observe("cpu", { sampleInterval: 1000 }).catch((error) => { status.textContent = `Pressure observation failed: ${error.name}`; mode.textContent = "Reduced workload"; }); } ``` Both the missing-interface branch and a rejected observation select the reduced workload. ### Checking a source and stopping observation Use `knownSources` as a hint before observing. Still handle rejection and disconnect when the work ends. ```js async function watchCpu(onRecords) { if (!("PressureObserver" in globalThis)) return null; if (!PressureObserver.knownSources.includes("cpu")) return null; const observer = new PressureObserver(onRecords); try { await observer.observe("cpu", { sampleInterval: 2000 }); return observer; } catch { observer.disconnect(); return null; } } const observer = await watchCpu((records) => console.log(records.at(-1)?.state)); document.addEventListener("visibilitychange", () => { if (document.hidden) observer?.disconnect(); }); ``` A `null` result gives the caller one fallback signal for an absent interface or unknown source. A rejected observation produces the same signal. ## See also - [Core Web Vitals](/reference/performance/core-web-vitals/) covers user-facing loading and interaction metrics - [Generic Sensor API](/reference/capabilities/sensors/), for device sensor observations - [Compute Pressure Level 1](https://w3c.github.io/compute-pressure/) (w3c.github.io) - [Compute Pressure API](https://developer.mozilla.org/en-US/docs/Web/API/Compute_Pressure_API) (MDN) --- # Contact Picker API URL: https://openpwa.net/reference/capabilities/contact-picker/ > navigator.contacts.select() opens a one-off contact picker. This reference covers syntax, errors, Android and iOS support, and form fallbacks. The `navigator.contacts.select()` method asks the user to choose contacts and the details to share with a page. The user agent presents the picker, and the page receives one-off access to the selected records instead of standing access to the address book. The `api.Navigator.contacts` and `api.ContactsManager` compatibility data records support from Chrome 80 on Android M (Android 6) and Android WebView 80. It records no support in desktop Chrome, Edge, Firefox, or macOS Safari; iOS 14.5 Safari has the `Contact Picker API` preference, and Samsung Internet 14.0 exposed an implementation that failed when opening the selector before removal in 22.0. MDN classifies the API as experimental and outside Baseline. The [Contact Picker compatibility data](/compatibility/contact-picker/) carries the browser rows and their verification date. ## Syntax The API exposes `select()` and `getProperties()` through `navigator.contacts` on a `[SecureContext]` interface in `Window`. `select()` must run in a top-level traversable with transient user activation. The specification defines `getProperties()` without those two checks. | Operation | Signature | Result | |---|---|---| | Pick contacts | `navigator.contacts.select(properties, options?)` | `Promise>` | | List available fields | `navigator.contacts.getProperties()` | `Promise>` | ```js navigator.contacts.select(properties) navigator.contacts.select(properties, options) navigator.contacts.getProperties() ``` Calling `select()` consumes transient activation before it opens the picker. The picker UI must display the requesting origin, identify the requested properties, let the user select individual contacts, and offer a cancel path. Cancellation returns an empty sequence. When `options.multiple` is false, the UI allows one contact to be picked. `getProperties()` reports the fields offered by the contact source chosen by the user agent. Use its result to build the array passed to `select()`; the specification rejects a selection request when that array contains a field outside the source's supported set. ## Parameters `select()` takes a sequence of contact fields and an optional selection dictionary. The Contact Picker specification defines the following values. | Parameter | Type | Required | Meaning | |---|---|---|---| | `properties` | `sequence` | Yes | Requested fields. The enum contains `"address"`, `"email"`, `"icon"`, `"name"`, and `"tel"`. | | `options.multiple` | `boolean` | No | Defaults to `false`. Set it to `true` to allow more than one selected contact. | Chrome documents `name`, `email`, and `tel` in Chrome 80 on Android M or later, with `address` and `icon` requiring Chrome 84 or later. Query `getProperties()` instead of assuming that every contact source supplies each enum value. The returned `ContactInfo` dictionary uses sequences because a selected contact can have more than one value for a field. A dictionary includes the fields requested by the caller. `ContactAddress` represents each physical address. | Member | Type | Content | |---|---|---| | `name` | `sequence` | Names from the selected contact | | `email` | `sequence` | Email addresses from the selected contact | | `tel` | `sequence` | Telephone numbers from the selected contact | | `address` | `sequence` | Physical addresses; the interface includes `country`, `addressLine`, `region`, `city`, and `postalCode`. W3C's 2021 activity records the change that transplanted `PaymentAddress` into `ContactInfo`. | | `icon` | `sequence` | Contact images represented by `Blob` objects | Chrome documents an empty sequence when the selected contact lacks a requested value or the user chooses not to share that value. The picker therefore does not tell the page which of those conditions produced the empty sequence. Chrome also documents that labels and other semantic information attached to contact fields are dropped. ## Exceptions The `select()` algorithm checks the calling context, user activation, picker state, and requested properties before presenting any UI. | Exception | Condition | |---|---| | `InvalidStateError` | The caller is not a top-level traversable, a picker is already showing for the navigable, or launching the picker or reading its contact source fails. | | `SecurityError` | The relevant global object has no transient activation. | | `TypeError` | `properties` is empty or includes a property that the contact source does not support. | Chromium's implementation reports a different exception when its Android selector cannot open: it rejects with `TypeError: Unable to open a contact selector`. Code that recovers from picker failures should handle the rejected promise rather than branching only on the exception names in the specification. A delayed callback can run after transient activation expires and then fail the implementation's activation check, so call `select()` as soon as practical within the activation handler. :::caution Chromium's [`contacts_manager.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/contacts_picker/contacts_manager.cc) emits `InvalidStateError: The contacts API can only be used in the top frame` outside the outermost main frame, `SecurityError: A user gesture is required to call this method` without transient activation, and `InvalidStateError: Contacts Picker is already in use.` for an overlapping call. Keep `select()` in the button handler and disable that button while its promise is pending. ::: ## Examples Both examples keep a form path available. Feature detection can decide which control to show, but a supported implementation can still reject or return a contact without the requested value. ### Picking one email with a manual fallback Place a button and an `` in the document. Test `'contacts' in navigator && 'ContactsManager' in window`, then call `select()` directly from the `click` handler. Treat an empty result as cancellation, and reveal the input after a missing email or rejected promise. ```js const pickButton = document.querySelector('#pick-recipient'); const manualField = document.querySelector('#recipient-email'); const supported = 'contacts' in navigator && 'ContactsManager' in window; pickButton.hidden = !supported; manualField.hidden = supported; pickButton.addEventListener('click', async () => { try { const [contact] = await navigator.contacts.select(['name', 'email']); if (!contact) return; // user cancelled const email = contact.email[0]; if (!email) { manualField.hidden = false; // contact had no email address return; } manualField.value = email; } catch (err) { console.error(`${err.name}: ${err.message}`); manualField.hidden = false; } }); ``` The input is the recovery path on unsupported browsers and after an error. Checking `contact.email[0]` also covers a contact whose email field is absent or withheld, as described by Chrome's Contact Picker documentation. ### Recovering when requested properties are unavailable Ask the contact source which values it supports before opening the picker. This function filters a desired list, passes `multiple: true`, returns `null` when the API or usable fields are absent, and leaves the caller to render its attendee form. A missing first value would otherwise produce `undefined`. ```js async function pickAttendees(wanted = ['name', 'tel', 'icon']) { if (!('contacts' in navigator && 'ContactsManager' in window)) { return null; // caller shows its own attendee form } const available = await navigator.contacts.getProperties(); const props = wanted.filter((p) => available.includes(p)); if (props.length === 0) return null; const contacts = await navigator.contacts.select(props, { multiple: true }); return contacts.map((c) => ({ name: c.name?.[0] ?? '', tel: c.tel?.[0] ?? '', avatar: c.icon?.[0] ? URL.createObjectURL(c.icon[0]) : null, })); } ``` Call this function from a user-activation handler because `select()` consumes transient activation. A `null` result tells the caller to display its form; an empty array means the picker returned no selected contact. Catch a rejection at the call site and show the same form, as the first example does. ## See also - [Contact Picker API browser support](/compatibility/contact-picker/) - [Web Share API](/reference/capabilities/web-share/) - [Payment Request API](/reference/capabilities/payment-request/) - [Contact Picker API](https://w3c.github.io/contact-picker/) (w3.org) - [A contact picker for the web](https://developer.chrome.com/docs/capabilities/web-apis/contact-picker) (developer.chrome.com) - [Chrome Platform Status: Contacts API](https://chromestatus.com/feature/6511327140904960) (chromestatus.com) --- # Credential Management API URL: https://openpwa.net/reference/capabilities/credential-management/ > navigator.credentials get(), store(), create(), and preventSilentAccess(): options, four mediation modes, every DOMException, and PasswordCredential gaps. The Credential Management API lets you retrieve, store, and create a `Credential` through `navigator.credentials`, or stop the browser from signing users in silently. The container accepts five credential types: `PasswordCredential`, `PublicKeyCredential` (WebAuthn), `OTPCredential`, `IdentityCredential` (FedCM), and the superseded `FederatedCredential`. `CredentialsContainer`, `get()`, and `store()` ship in Chrome 51, Edge 18, Firefox 60, and Safari 13; `create()` in Chrome 60; `preventSilentAccess()` in Chrome 60 (Chrome 51 to 59 called it `requireUserMediation()`), Edge 18, Firefox 60, and Safari 17, with Safari 13 to 16 exposing a method that rejects every call with `NotSupportedError` (BCD `api.CredentialsContainer`). Support for individual credential types is more limited: `PasswordCredential` exists in Chrome 51 and in no version of Firefox or Safari; `get({ otp })` in Chrome 93 (Chrome 84 on Android) and Safari 27; `get({ identity })` in Chrome 108 and Safari 27. `PublicKeyCredential` is the WebAuthn credential type. ## Syntax ```js navigator.credentials.get() navigator.credentials.get(options) navigator.credentials.store(credential) navigator.credentials.create() navigator.credentials.create(options) navigator.credentials.preventSilentAccess() ``` `get()` and `create()` return `Promise`: a `Credential` subclass instance, or `null` when nothing could be obtained or created without more user involvement than `mediation` allows. `store()` and `preventSilentAccess()` return `Promise`. All four are `[SecureContext]`; the container is `undefined` on `http://` origins other than `localhost`. ## Parameters `get()` takes a `CredentialRequestOptions`, `create()` a `CredentialCreationOptions`, `store()` a `Credential`, and `preventSilentAccess()` nothing. Each credential type adds its own member to the two dictionaries; a request names exactly the types it will accept by including their members. | Member | Type | Required | Description | |---|---|---|---| | `mediation` (get, create) | `"silent"`, `"optional"`, `"conditional"`, or `"required"` | No | Default `"optional"`. `"silent"` resolves `null` rather than showing UI; `"optional"` shows a chooser only when needed; `"conditional"` surfaces discovered credentials in a non-modal UI (autofill) and does not resolve `null` promptly; `"required"` ignores any silent-access opt-in and prompts. For `create()`, `"conditional"` lets a recently mediated sign-in create without a modal, else rejects. | | `uiMode` (get) | `DOMString` | No | `"immediate"`: show a modal chooser if credentials exist, otherwise complete at once with `null` and no prompt. | | `signal` (get, create) | `AbortSignal` | No | Aborting rejects with the signal's reason (`AbortError` by default, `TimeoutError` from `AbortSignal.timeout()`), unless the operation already finished. | | `password` (get) | `boolean` | No | Default `false`. `true` asks for a stored `PasswordCredential`. | | `password` (create) | `PasswordCredentialData` or `HTMLFormElement` | No | `PasswordCredentialData` has `id` (required), `origin` (required), `password` (required), `name`, and `iconURL`; a form is read through its `autocomplete` tokens. | | `federated` (get, create) | `FederatedCredentialRequestOptions` / `FederatedCredentialInit` | No | `providers: sequence` and `protocols: sequence` for the superseded `FederatedCredential`. | | `publicKey` (get, create) | `PublicKeyCredentialRequestOptions` / `PublicKeyCredentialCreationOptions` | No | WebAuthn; documented under WebAuthn and passkeys. | | `otp` (get) | `OTPCredentialRequestOptions` | No | `transport: ["sms"]`; resolves an `OTPCredential` whose `code` is the SMS one-time code. | | `identity` (get) | `IdentityCredentialRequestOptions` | No | `providers` with `configURL`, `clientId`, and optional `nonce`, `loginHint`, `domainHint`; FedCM. | The `credential` argument to `store()` must be a `Credential` the page obtained from `get()` or built itself (`new PasswordCredential(data)` or `new PasswordCredential(form)`). ## Exceptions The algorithms reject in a fixed order. Any rejection the credential type's own internal methods throw (for example WebAuthn's `NotAllowedError` on timeout) is passed through unchanged. | Exception | Condition | |---|---| | `InvalidStateError` | The document is not fully active (all four methods). Chromium also uses it when another request on the same container is in flight. | | `NotSupportedError` | `get()` with no type member, or two members whose types cannot share a request; `create()` with more than one type member or without an associated document. Safari 13 to 16 reject every `preventSilentAccess()` call with it, and Chromium rejects with it when the password store is unavailable. | | `SecurityError` | An origin-bound type (`PasswordCredential`, `FederatedCredential`) requested, created, or stored from an opaque origin. | | `TypeError` | `mediation: "conditional"` or `uiMode: "immediate"` with a type that does not support it; `create({ password })` whose data or form cannot build a `PasswordCredential`. | | `NotAllowedError` | A request for a type that is already active in this settings object; the type's Permissions Policy denies the document; `PasswordCredential` collection or storage from a context that is not same-origin with all its ancestors; `create()` with `mediation: "conditional"` without prior consent. | | The signal's abort reason | `options.signal` was already aborted when `get()` or `create()` ran, or fired before the operation finished. | `preventSilentAccess()` resolves even when the browser stores no credentials; its only specified rejection is `InvalidStateError`. :::caution Chromium's [`authentication_credentials_container.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/credentialmanagement/authentication_credentials_container.cc) maps browser-side errors to these rejections. `CredentialManagerErrorToDOMException` produces `InvalidStateError: A request is already pending.` for a pending request and `NotSupportedError: The password store is unavailable.` when the password store cannot be used. For FedCM, `OnRequestToken` rejects with `NotAllowedError: Only one navigator.credentials.get request may be outstanding at one time.` when too many requests are in flight. ::: ## Examples The examples test for `PasswordCredential` as well as `navigator.credentials`, because Firefox 60+ and Safari 13+ ship the container without that type: `'credentials' in navigator` passes and `get({ password: true })` resolves `null`. ### Signing in silently on arrival, with a deadline and a visible fallback `mediation: "silent"` shows no chooser; it resolves `null` when consent would be needed, so the page can show its normal sign-in button. `AbortSignal.timeout()` turns a store that hangs into a `TimeoutError`. ```js async function trySilentSignIn() { if (!('credentials' in navigator) || !('PasswordCredential' in window)) { showSignInButton(); return; } try { const cred = await navigator.credentials.get({ password: true, mediation: 'silent', signal: AbortSignal.timeout(5000), }); if (!cred) return showSignInButton(); await postJson('/session', { id: cred.id, password: cred.password }); showSignedInState(cred.name ?? cred.id); } catch (err) { if (err.name === 'TimeoutError' || err.name === 'AbortError') return showSignInButton(); throw err; } } window.addEventListener('load', trySilentSignIn); ``` Branch on both `TimeoutError` and `AbortError`: `AbortSignal.timeout()` rejects with the former, a manual `AbortController` with the latter. ### Remembering a password after a successful form sign-in `store()` after the server accepted the credentials is what lets the next visit's silent `get()` succeed. Build the `PasswordCredential` from the form so the `autocomplete="username"` and `autocomplete="current-password"` fields supply `id` and `password`. ```js document.querySelector('#sign-in').addEventListener('submit', async (event) => { event.preventDefault(); const form = event.currentTarget; const ok = await postForm('/session', new FormData(form)); if (!ok) return showError('Wrong username or password'); if ('PasswordCredential' in window) { try { await navigator.credentials.store(new PasswordCredential(form)); } catch (err) { console.warn(`store() failed: ${err.name}`); // sign-in already succeeded } } location.assign('/home'); }); ``` Chrome 51+ is the only engine where this branch runs; in Firefox and Safari the form submits normally and the browser's own password manager offers to save. ### Clearing silent access on sign-out, including Safari 13 to 16 `preventSilentAccess()` sets the origin's flag so the next `get()` requires mediation. A `typeof` check passes in Safari 13 to 16 even though every call rejects with `NotSupportedError`, so catch that one name and treat it as done. ```js async function signOut() { await fetch('/session', { method: 'DELETE' }); if (typeof navigator.credentials?.preventSilentAccess === 'function') { try { await navigator.credentials.preventSilentAccess(); } catch (err) { if (err.name !== 'NotSupportedError') throw err; } } location.assign('/'); } ``` Only `NotSupportedError` is swallowed; an `InvalidStateError` from a detached document still surfaces. ## See also - [WebAuthn and passkeys](/reference/capabilities/webauthn-passkeys/), for the `PublicKeyCredential` type - [Payment Request API](/reference/capabilities/payment-request/), the kind of step that calls for `mediation: "required"` first - [Web app manifest id: a stable PWA identity](/reference/manifest/id/), identifies the installed app, not the user - [Credential Management Level 1: Request a Credential](https://www.w3.org/TR/credential-management-1/#abstract-opdef-request-a-credential) (w3.org) - [The Credential Management API](https://web.dev/articles/security-credential-management) (web.dev) - [Chrome Platform Status: Credential Management API](https://chromestatus.com/feature/5026422640869376) (chromestatus.com) --- # Device Posture API (foldables) URL: https://openpwa.net/reference/capabilities/device-posture/ > How navigator.devicePosture exposes continuous and folded posture states, reports changes, and falls back to a single-pane layout when unavailable. The `navigator.devicePosture` property exposes a `DevicePosture` object for reading the applied posture and receiving posture changes. The specification defines `"continuous"` and `"folded"` values. ## Where it is supported BCD records the API from Chrome 132 and Samsung Internet 16.2, with Chromium-derived entries mirrored from Chrome. It records no support in Firefox or desktop Safari; Safari on iOS 27 records support behind the `DevicePostureEnabled` preference. ## Syntax ```js const posture = navigator.devicePosture.type; navigator.devicePosture.addEventListener('change', handlePostureChange); ``` The specification exposes `navigator.devicePosture` to `Window` in secure contexts. ## Members | Member | Type | Meaning | |---|---|---| | `type` | `DevicePostureType` | Returns the document's current applied posture as `"continuous"` or `"folded"`. | | `change` | event | Fires on the `DevicePosture` object after the applied posture changes. | The `DevicePosture` interface inherits from `EventTarget`. The `devicePosture` property returns the same object on repeated access, as specified by `[SameObject]`. ## Exceptions None. :::caution The device-posture change steps stop while the document is hidden. The specification says the document receives the change event after it becomes visible again; reading the value while hidden can therefore return a stale posture ([Device Posture change](https://w3c.github.io/device-posture/#device-posture-change)). ::: ## Examples These examples preserve a single-pane layout when posture information is unavailable or does not report a fold. ### Switching between folded and single-pane layouts This example detects the API, applies the current posture, and uses a single-pane class when the API is unavailable. ```js function applyPosture(type) { document.documentElement.classList.toggle('is-folded', type === 'folded'); document.documentElement.classList.toggle('is-single-pane', type !== 'folded'); } if ('devicePosture' in navigator) { applyPosture(navigator.devicePosture.type); navigator.devicePosture.addEventListener('change', () => { applyPosture(navigator.devicePosture.type); }); } else { applyPosture('continuous'); } ``` The fallback selects the same single-pane layout used for the specified `"continuous"` value. It does not infer whether the physical device can fold. ### Adapting with a media query The specification also defines the `device-posture` media feature. This rule changes the layout only when the user agent reports `folded`. ```css .workspace { display: block; } @media (device-posture: folded) { .workspace { display: grid; grid-template-columns: 1fr 1fr; } } ``` When the media feature is unsupported or does not match, the block layout remains in effect. ## See also - [Screen Orientation API](/reference/capabilities/screen-orientation-api/) - [orientation manifest member](/reference/manifest/orientation/) - [Device Posture API specification (W3C)](https://w3c.github.io/device-posture/) - [DevicePosture (MDN)](https://developer.mozilla.org/en-US/docs/Web/API/DevicePosture) --- # Digital Goods API URL: https://openpwa.net/reference/capabilities/digital-goods/ > window.getDigitalGoodsService() exposes Google Play Billing to a PWA in a Trusted Web Activity: getDetails(), listPurchases(), consume(), errors, fallbacks. The Digital Goods API reads a web app's store catalogue and the user's purchases from the store back end. `window.getDigitalGoodsService(provider)` returns a `DigitalGoodsService`; its `getDetails()`, `listPurchases()`, `listPurchaseHistory()`, and `consume()` methods communicate with that provider. Purchases run through the Payment Request API, using the same provider URL as the payment method. The Chrome for Developers guide describes the API as available in Chrome 101 and above on Android and ChromeOS, and as currently supported only by Chrome when the PWA runs inside a Trusted Web Activity, with `https://play.google.com/billing` as the provider. The guide also describes a Chrome flag for testing on a development device. The specification is a WICG draft, and it says user agents that do not support Digital Goods should not expose `getDigitalGoodsService()` on `Window`, so an `in` check is the feature test; a successful call can still reject where the provider is unsupported. ## Syntax ```js window.getDigitalGoodsService(serviceProvider) digitalGoodsService.getDetails(itemIds) digitalGoodsService.listPurchases() digitalGoodsService.listPurchaseHistory() digitalGoodsService.consume(purchaseToken) ``` `getDigitalGoodsService()` returns `Promise`. `getDetails()` returns `Promise>`, `listPurchases()` and `listPurchaseHistory()` return `Promise>`, and `consume()` returns `Promise`. Everything is `[SecureContext]` and `Window`-only; no method needs a user gesture, but the document must be same-origin with the top-level page and allowed to use the `payment` Permissions Policy feature (a same-site iframe needs `allow="payment"`). ## Parameters Three methods take an argument; the two list methods take none. | Parameter | Type | Required | Description | |---|---|---|---| | `serviceProvider` | `DOMString` | Yes | A URL-based payment method identifier; for Google Play it is `"https://play.google.com/billing"`. `undefined`, `null`, or `""` rejects. | | `itemIds` | `sequence` | Yes | Product or subscription IDs as configured in the store console. Must be non-empty; the result may omit unknown IDs and may be in any order. | | `purchaseToken` | `DOMString` | Yes | A token returned by `listPurchases()` or by the `PaymentResponse.details` of the purchase. Must be non-empty. | `getDetails()` resolves `ItemDetails` dictionaries with these members: | Member | Type | Required | Description | |---|---|---|---| | `itemId` | `DOMString` | Yes | The ID that was requested. | | `title` | `DOMString` | Yes | Localized name for display. | | `price` | `PaymentCurrencyAmount` | Yes | `{ currency, value }` in the user's region; format with `Intl.NumberFormat`. | | `type` | `"product"` or `"subscription"` | No | Item kind. | | `description` | `DOMString` | No | Localized long description. | | `iconURLs` | `sequence` | No | Item images. | | `subscriptionPeriod` | `DOMString` | No | ISO 8601 duration, subscriptions only. | | `freeTrialPeriod` | `DOMString` | No | ISO 8601 duration of the free trial. | | `introductoryPrice` | `PaymentCurrencyAmount` | No | Price during the introductory period. | | `introductoryPricePeriod` | `DOMString` | No | ISO 8601 duration of that period. | | `introductoryPriceCycles` | `unsigned long long` | No | Number of billing cycles the introductory price applies. | `listPurchases()` and `listPurchaseHistory()` resolve `PurchaseDetails` dictionaries with two required members, `itemId` and `purchaseToken`; `listPurchaseHistory()` may include consumed or expired purchases, and a store without history returns the same list as `listPurchases()`. ## Exceptions These methods report errors by rejecting their promises; they do not throw synchronously. Chromium's `OperationError` messages are the literal Play Billing response codes, which is the only way to tell "item already owned" from "store app missing". | Exception | Condition | |---|---| | `InvalidStateError` | `getDigitalGoodsService()` from a document that is not fully active. | | `NotAllowedError` | `getDigitalGoodsService()` from a document that is not same-origin with the top-level origin, or that the `payment` Permissions Policy does not allow. | | `TypeError` | `getDigitalGoodsService()` with an `undefined`, `null`, or empty provider; `getDetails([])`; `consume("")`. | | `OperationError` | `getDigitalGoodsService()` when the provider is unsupported in this context (outside a TWA, or Play Billing not enabled in the package); any of the four service methods when the store reports an error. Chromium message strings: `unsupported payment method`, `unsupported context`, `error`, `itemAlreadyOwned`, `itemNotOwned`, `itemUnavailable`, `clientAppUnavailable`, `clientAppError`. | A `PaymentRequest.show()` on the same provider rejects with `AbortError` when the user backs out of the Play purchase sheet; that is the Payment Request API's exception, not this one's. :::caution Chromium's [`dom_window_digital_goods.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/payments/goods/dom_window_digital_goods.cc) rejects `getDigitalGoodsService()` before it contacts the browser in three cases, in addition to the `InvalidStateError` it raises for an invalid or destroyed execution context. A call from a cross-site frame fails with `NotAllowedError: Access denied from cross-site frames`, a frame without the `payment` permissions policy fails with `NotAllowedError: Payment permissions policy not granted`, and an empty payment method fails with `TypeError: Empty payment method`. When the browser refuses to create the service, the promise rejects with an `OperationError` whose message comes from the response code in [`digital_goods_type_converters.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/payments/goods/digital_goods_type_converters.cc): `error`, `unsupported payment method`, or `unsupported context`. ::: ## Examples Use a shared helper that resolves `null` outside a Play-backed Trusted Web Activity. The app can then show web checkout through Stripe, PayPal, or a plain form. ### Getting the Play service or falling back to web checkout The `in` check tells you the browser implements the API; only the resolved promise tells you Play Billing is reachable from this package. Treat either failure the same way. ```js const PLAY_BILLING = 'https://play.google.com/billing'; async function getPlayService() { if (!('getDigitalGoodsService' in window)) return null; try { return await window.getDigitalGoodsService(PLAY_BILLING); } catch (err) { console.info(`Play Billing unavailable (${err.name}: ${err.message})`); return null; } } const service = await getPlayService(); document.querySelector('#web-checkout').hidden = Boolean(service); document.querySelector('#play-checkout').hidden = !service; ``` Logging `err.message` keeps the Play response code (`unsupported context`, `clientAppUnavailable`) in your telemetry without changing what the user sees. ### Rendering prices from getDetails() in the user's locale `price` arrives as a `PaymentCurrencyAmount`; format it with `Intl.NumberFormat` instead of concatenating `value` and `currency` yourself. Missing IDs are absent from the result. Iterate the response to render the returned items. ```js async function renderCatalogue(service, ids) { if (!service) return renderWebPrices(ids); // fetched from your own server const items = await service.getDetails(ids); const money = new Intl.NumberFormat(navigator.language, { style: 'currency', currency: items[0]?.price.currency ?? 'USD' }); for (const item of items) { const row = document.createElement('li'); row.textContent = `${item.title}: ${money.format(item.price.value)}`; if (item.type === 'subscription' && item.freeTrialPeriod) { row.textContent += ` (trial ${item.freeTrialPeriod})`; } document.querySelector('#catalogue').append(row); } } ``` A trial period such as `P7D` is an ISO 8601 duration string; format it yourself, `Intl` has no duration formatter for it in Chrome 101. ### Buying with PaymentRequest, then restoring entitlements with listPurchases() The purchase flow is Payment Request with `supportedMethods` set to the provider URL and the SKU in `data`; Play ignores the `total` you must still supply. Acknowledge the `purchaseToken` on your server: Google Play refunds and revokes any purchase left unacknowledged for three days (Chrome for Developers guide). On later launches, `listPurchases()` returns what the user already owns, including purchases made on another device. ```js async function buy(service, sku) { if (!service) return startWebCheckout(sku); const request = new PaymentRequest( [{ supportedMethods: PLAY_BILLING, data: { sku } }], { total: { label: 'Total', amount: { currency: 'USD', value: '0' } } }, ); try { const response = await request.show(); const { purchaseToken } = response.details; const verified = await postJson('/play/acknowledge', { sku, purchaseToken }); await response.complete(verified ? 'success' : 'fail'); if (verified) await service.consume(purchaseToken); // consumables only } catch (err) { if (err.name !== 'AbortError') throw err; // the user left the Play purchase sheet } } async function restoreEntitlements(service) { if (!service) return []; const owned = await service.listPurchases(); return (await postJson('/play/verify', owned)).filter((p) => p.valid).map((p) => p.itemId); } ``` `consume()` is only for items designed to be bought repeatedly: the specification states that the user is expected to lose the entitlement once a purchase is consumed, so do not call it on a subscription or a permanent upgrade. ## See also - [Payment Request API](/reference/capabilities/payment-request/), the purchase half of the flow - [Trusted Web Activity (TWA): PWAs in the Play Store](/reference/installation/twa/), the container the API requires - [Monetize a PWA](/guides/monetization/) - [Digital Goods API: getDigitalGoodsService() method](https://wicg.github.io/digital-goods/#getdigitalgoodsservice-method) (wicg.github.io) - [Receive Payments via Google Play Billing with the Digital Goods API and the Payment Request API](https://developer.chrome.com/docs/android/trusted-web-activity/receive-payments-play-billing/) (developer.chrome.com) - [Chrome Platform Status: Digital Goods API](https://chromestatus.com/feature/5339955595313152) (chromestatus.com) --- # Document Picture-in-Picture API URL: https://openpwa.net/reference/capabilities/document-picture-in-picture/ > documentPictureInPicture.requestWindow() opens an always-on-top window holding arbitrary HTML. Options, the exceptions it rejects with, examples with fallbacks. `window.documentPictureInPicture.requestWindow()` opens a same-origin, always-on-top window whose `document` you can fill with arbitrary HTML. The older Picture-in-Picture API accepts a single `