repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/api/interventionreportbody | data/mdn-content/files/en-us/web/api/interventionreportbody/message/index.md | ---
title: "InterventionReportBody: message property"
short-title: message
slug: Web/API/InterventionReportBody/message
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.InterventionReportBody.message
---
{{APIRef("Reporting API")}}{{SeeCompatTable}}
The **`message`** read-only property of the {{domxref("InterventionReportBody")}} interface returns a human-readable description of the intervention, including information such as how the intervention could be avoided. This typically matches the message a browser will display in its DevTools console when an intervention is imposed, if one is available.
## Value
A string.
## Examples
In this example we create a new {{domxref("ReportingObserver")}} to observe intervention reports, then print the value of `message` to the console.
```js
const options = {
types: ["intervention"],
buffered: true,
};
const observer = new ReportingObserver((reports, observer) => {
const firstReport = reports[0];
console.log(firstReport.type); // intervention
console.log(firstReport.body.message);
}, options);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/interventionreportbody | data/mdn-content/files/en-us/web/api/interventionreportbody/id/index.md | ---
title: "InterventionReportBody: id property"
short-title: id
slug: Web/API/InterventionReportBody/id
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.InterventionReportBody.id
---
{{APIRef("Reporting API")}}{{SeeCompatTable}}
The **`id`** read-only property of the {{domxref("InterventionReportBody")}} interface returns a string identifying the intervention that generated the report. This can be used to group reports.
## Value
A string.
## Examples
In this example we create a new {{domxref("ReportingObserver")}} to observe intervention reports, then print the value of `id` to the console.
```js
const options = {
types: ["intervention"],
buffered: true,
};
const observer = new ReportingObserver((reports, observer) => {
const firstReport = reports[0];
console.log(firstReport.type); // intervention
console.log(firstReport.body.id);
}, options);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/interventionreportbody | data/mdn-content/files/en-us/web/api/interventionreportbody/tojson/index.md | ---
title: "InterventionReportBody: toJSON() method"
short-title: toJSON()
slug: Web/API/InterventionReportBody/toJSON
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.InterventionReportBody.toJSON
---
{{APIRef("Reporting API")}}{{SeeCompatTable}}
The **`toJSON()`** method of the {{domxref("InterventionReportBody")}} interface is a _serializer_, and returns a JSON representation of the `InterventionReportBody` object.
## Syntax
```js-nolint
toJSON()
```
### Parameters
None.
### Return value
A JSON object that is the serialization of the {{domxref("InterventionReportBody")}} object.
## Examples
In this example we create a new {{domxref("ReportingObserver")}} to observe intervention reports, then return a JSON representation of the first entry.
```js
const options = {
types: ["intervention"],
buffered: true,
};
const observer = new ReportingObserver((reports, observer) => {
const firstReport = reports[0];
console.log(firstReport.toJSON());
}, options);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/interventionreportbody | data/mdn-content/files/en-us/web/api/interventionreportbody/sourcefile/index.md | ---
title: "InterventionReportBody: sourceFile property"
short-title: sourceFile
slug: Web/API/InterventionReportBody/sourceFile
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.InterventionReportBody.sourceFile
---
{{APIRef("Reporting API")}}{{SeeCompatTable}}
The **`sourceFile`** read-only property of the {{domxref("InterventionReportBody")}} interface returns the path to the source file where the intervention occurred.
> **Note:** This property can be used with {{domxref("InterventionReportBody.lineNumber")}} and {{domxref("InterventionReportBody.columnNumber")}} to locate the column and line in the file where the feature is used.
## Value
A string, or `null` if the path is not known.
## Examples
In this example we create a new {{domxref("ReportingObserver")}} to observe intervention reports, then print the value of `sourceFile` to the console.
```js
const options = {
types: ["intervention"],
buffered: true,
};
const observer = new ReportingObserver((reports, observer) => {
const firstReport = reports[0];
console.log(firstReport.type); // intervention
console.log(firstReport.body.sourceFile);
}, options);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/permissions/index.md | ---
title: Permissions
slug: Web/API/Permissions
page-type: web-api-interface
browser-compat: api.Permissions
---
{{APIRef("Permissions API")}} {{AvailableInWorkers}}
The Permissions interface of the [Permissions API](/en-US/docs/Web/API/Permissions_API) provides the core Permission API functionality, such as methods for querying and revoking permissions
## Instance methods
- {{domxref("Permissions.query","Permissions.query()")}}
- : Returns the user permission status for a given API.
- {{domxref("Permissions.request","Permissions.request()")}} {{Experimental_Inline}}
- : Requests permission to use a given API. This is not currently supported in any browser.
- {{domxref("Permissions.requestAll","Permissions.requestAll()")}} {{Experimental_Inline}} {{Non-standard_Inline}}
- : Requests permission to use a given set of APIs. This is not currently supported in any browser.
- {{domxref("Permissions.revoke","Permissions.revoke()")}} {{Deprecated_Inline}}
- : Revokes the permission currently set on a given API.
## Example
```js
navigator.permissions.query({ name: "geolocation" }).then((result) => {
if (result.state === "granted") {
showLocalNewsWithGeolocation();
} else if (result.state === "prompt") {
showButtonToEnableLocalNews();
}
// Don't do anything if the permission was denied.
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/permissions | data/mdn-content/files/en-us/web/api/permissions/revoke/index.md | ---
title: "Permissions: revoke() method"
short-title: revoke()
slug: Web/API/Permissions/revoke
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.Permissions.revoke
---
{{APIRef("Permissions API")}}{{deprecated_header}}
The **`Permissions.revoke()`** method of the
{{domxref("Permissions")}} interface reverts a currently set permission back to its
default state, which is usually `prompt`.
This method is called on the global {{domxref("Permissions")}} object
{{domxref("navigator.permissions")}}.
## Syntax
```js-nolint
revoke(descriptor)
```
### Parameters
- `descriptor`
- : An object based on the `PermissionDescriptor` dictionary that sets
options for the operation consisting of a comma-separated list of name-value pairs.
The available options are:
- `name`
- : The name of the API whose permissions you want to query.
Valid values are `'geolocation'`, `'midi'`,
`'notifications'`, and `'push'`.
- `userVisibleOnly`
- : (Push only, not supported in Firefox — see the
[Browser compatibility](#browser_compatibility) section below) Indicates whether you want to
show a notification for every message or be able to send silent push
notifications. The default is `false`.
- `sysex` (MIDI only)
- : Indicates whether you need and/or receive system
exclusive messages. The default is `false`.
> **Note:** As of Firefox 44, the permissions for [Notifications](/en-US/docs/Web/API/Notifications_API) and [Push](/en-US/docs/Web/API/Push_API) have been merged. If permission is
> granted (e.g. by the user, in the relevant permissions dialog),
> `navigator.permissions.query()` will return `true` for both
> `notifications` and `push`.
> **Note:** The `persistent-storage` permission allows an
> origin to use a persistent box (i.e., [persistent storage](https://storage.spec.whatwg.org/#persistence)) for its
> storage, as per the [Storage API](https://storage.spec.whatwg.org/).
### Return value
A {{jsxref("Promise")}} that calls its fulfillment handler with a
{{domxref("PermissionStatus")}} object indicating the result of the request.
### Exceptions
- {{jsxref("TypeError")}}
- : Retrieving the `PermissionDescriptor` information failed in some way, or
the permission doesn't exist or is currently unsupported (e.g. `midi`, or
`push` with `userVisibleOnly`).
## Examples
This function can be used by an app to request that its own Geolocation API permission
be revoked.
```js
function revokePermission() {
navigator.permissions.revoke({ name: "geolocation" }).then((result) => {
report(result.state);
});
}
```
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/permissions | data/mdn-content/files/en-us/web/api/permissions/query/index.md | ---
title: "Permissions: query() method"
short-title: query()
slug: Web/API/Permissions/query
page-type: web-api-instance-method
browser-compat: api.Permissions.query
---
{{APIRef("Permissions API")}}
The **`Permissions.query()`** method of the {{domxref("Permissions")}} interface returns the state of a user permission on the global scope.
## Syntax
```js-nolint
query(permissionDescriptor)
```
### Parameters
- `permissionDescriptor`
- : An object that sets options for the `query` operation consisting of a comma-separated list of name-value pairs. The available options are:
- `name`
- : The name of the API whose permissions you want to query. Each browser supports a different set of values. You'll find Firefox values [there](https://searchfox.org/mozilla-central/source/dom/webidl/Permissions.webidl#10), Chromium values [there](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/third_party/blink/renderer/modules/permissions/permission_descriptor.idl), and WebKit values [there](https://github.com/WebKit/WebKit/blob/main/Source/WebCore/Modules/permissions/PermissionName.idl).
- `userVisibleOnly`
- : (Push only, not supported in Firefox — see the Browser Support section below) Indicates whether you want to show a notification for every message or be able to send silent push notifications. The default is `false`.
- `sysex` (Midi only)
- : Indicates whether you need and/or receive system exclusive messages. The default is `false`.
> **Note:** As of Firefox 44, the permissions for [Notifications](/en-US/docs/Web/API/Notifications_API) and [Push](/en-US/docs/Web/API/Push_API) have been merged. If permission is granted (e.g. by the user, in the relevant permissions dialog), `navigator.permissions.query()` will return `true` for both `notifications` and `push`.
> **Note:** The `persistent-storage` permission allows an origin to use a persistent box (i.e., [persistent storage](https://storage.spec.whatwg.org/#persistence)) for its storage, as per the [Storage API](https://storage.spec.whatwg.org/).
### Return value
A {{jsxref("Promise")}} that resolves to a {{domxref("PermissionStatus")}} object.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if `query()` method is invoked in the browsing context and its associated document is not fully active.
- {{jsxref("TypeError")}}
- : Thrown if retrieving the `PermissionDescriptor` information failed in some way, or the permission doesn't exist or is unsupported by the user agent.
## Examples
### Display news based on geolocation permission
This example shows how you might display news related to the current location if the `geolocation` permission is granted, and otherwise prompt the user to enable granting access to the location.
```js
navigator.permissions.query({ name: "geolocation" }).then((result) => {
if (result.state === "granted") {
showLocalNewsWithGeolocation();
} else if (result.state === "prompt") {
showButtonToEnableLocalNews();
}
// Don't do anything if the permission was denied.
});
```
### Test support for various permissions
This example shows the result of querying each of the permissions.
The code uses `navigator.permissions.query()` to query each permission, logging either the permission status or the fact that the permission is not supported on the browser.
Note that the `query()` is called inside a `try...catch` block because the associated `Promise` will reject if the permission is not supported.
```html hidden
<pre id="log"></pre>
```
```js hidden
const logElement = document.querySelector("#log");
function log(text) {
logElement.innerText = `${logElement.innerText}${text}\n`;
logElement.scrollTop = logElement.scrollHeight;
}
```
```css hidden
#log {
height: 320px;
overflow: scroll;
padding: 0.5rem;
border: 1px solid black;
}
```
```js
// Array of permissions
const permissions = [
"accelerometer",
"accessibility-events",
"ambient-light-sensor",
"background-sync",
"camera",
"clipboard-read",
"clipboard-write",
"geolocation",
"gyroscope",
"local-fonts",
"magnetometer",
"microphone",
"midi",
"notifications",
"payment-handler",
"persistent-storage",
"push",
"screen-wake-lock",
"storage-access",
"top-level-storage-access",
"window-management",
];
processPermissions();
// Iterate through the permissions and log the result
async function processPermissions() {
for (const permission of permissions) {
const result = await getPermission(permission);
log(result);
}
}
// Query a single permission in a try...catch block and return result
async function getPermission(permission) {
try {
const result = await navigator.permissions.query({ name: permission });
return `${permission}: ${result.state}`;
} catch (error) {
return `${permission} (not supported)`;
}
}
```
The log from running the code is shown below:
{{EmbedLiveSample('Test support for various permissions',"100%", "370px")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/css/index.md | ---
title: CSS
slug: Web/API/CSS
page-type: web-api-interface
browser-compat: api.CSS
spec-urls:
- https://drafts.csswg.org/cssom/#namespacedef-css
- https://www.w3.org/TR/css-properties-values-api-1/
---
{{APIRef("CSSOM")}}
The **`CSS`** interface holds useful CSS-related methods. No objects with this interface are implemented: it contains only static methods and is therefore a utilitarian interface.
## Static properties
- {{DOMxRef("CSS/highlights_static", "CSS.highlights")}}
- : Provides access to the `HighlightRegistry` used to style arbitrary text ranges using the {{domxref("css_custom_highlight_api", "CSS Custom Highlight API", "", "nocode")}}.
- {{DOMxRef("CSS/paintWorklet_static", "CSS.paintWorklet")}} {{Experimental_Inline}} {{SecureContext_Inline}}
- : Provides access to the Worklet responsible for all the classes related to painting.
## Instance properties
_The CSS interface is a utility interface and no object of this type can be created: only static properties are defined on it._
## Static methods
_No inherited static methods_.
- {{DOMxRef("CSS/registerProperty_static", "CSS.registerProperty()")}}
- : Registers {{cssxref('--*', 'custom properties')}}, allowing for property type checking, default values, and properties that do or do not inherit their value.
- {{DOMxRef("CSS/supports_static", "CSS.supports()")}}
- : Returns a boolean value indicating if the pair _property-value_, or the condition, given in parameter is supported.
- {{DOMxRef("CSS/escape_static", "CSS.escape()")}}
- : Can be used to escape a string mostly for use as part of a CSS selector.
- {{DOMxRef("CSS/factory_functions_static", 'CSS factory functions')}}
- : Can be used to return a new [`CSSUnitValue`](/en-US/docs/Web/API/CSSUnitValue) with a value of the parameter number of the units of the name of the factory function method used.
```js
CSS.em(3); // CSSUnitValue {value: 3, unit: "em"}
```
## Instance methods
_The CSS interface is a utility interface and no object of this type can be created: only static methods are defined on it._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/css | data/mdn-content/files/en-us/web/api/css/highlights_static/index.md | ---
title: "CSS: highlights static property"
short-title: highlights
slug: Web/API/CSS/highlights_static
page-type: web-api-static-property
browser-compat: api.CSS.highlights_static
---
{{APIRef("CSSOM")}}
The static, read-only **`highlights`** property of the {{domxref("CSS")}} interface provides access to the `HighlightRegistry` used to style arbitrary text ranges using the {{domxref("css_custom_highlight_api", "CSS Custom Highlight API", "", "nocode")}}.
## Value
The {{DOMxRef("HighlightRegistry")}} object.
## Examples
The following example demonstrates creating multiple text ranges, then creating a `Highlight` object for them, registering this highlight in the `HighlightRegistry`, and finally styling the text ranges using the {{cssxref("::highlight", "::highlight()")}} pseudo-element.
```js
const parentNode = document.getElementById("foo");
const range1 = new Range();
range1.setStart(parentNode, 10);
range1.setEnd(parentNode, 20);
const range2 = new Range();
range2.setStart(parentNode, 40);
range2.setEnd(parentNode, 60);
const myCustomHighlight = new Highlight(range1, range2);
CSS.highlights.set("my-custom-highlight", myCustomHighlight);
```
```css
::highlight(my-custom-highlight) {
background-color: yellow;
color: black;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("css_custom_highlight_api", "The CSS Custom Highlight API", "", "nocode")}}
- [CSS Custom Highlight API: The Future of Highlighting Text Ranges on the Web](https://css-tricks.com/css-custom-highlight-api-early-look/)
| 0 |
data/mdn-content/files/en-us/web/api/css | data/mdn-content/files/en-us/web/api/css/escape_static/index.md | ---
title: "CSS: escape() static method"
short-title: escape()
slug: Web/API/CSS/escape_static
page-type: web-api-static-method
browser-compat: api.CSS.escape_static
---
{{APIRef("CSSOM")}}
The **`CSS.escape()`** static method returns a
string containing the escaped string passed as parameter, mostly for
use as part of a CSS selector.
## Syntax
```js-nolint
CSS.escape(str)
```
### Parameters
- `str`
- : The string to be escaped.
### Return value
The escaped string.
## Examples
### Basic results
```js-nolint
CSS.escape(".foo#bar"); // "\\.foo\\#bar"
CSS.escape("()[]{}"); // "\\(\\)\\[\\]\\{\\}"
CSS.escape('--a'); // "--a"
CSS.escape(0); // "\\30 ", the Unicode code point of '0' is 30
CSS.escape('\0'); // "\ufffd", the Unicode REPLACEMENT CHARACTER
```
### In context uses
To escape a string for use as part of a selector, the `escape()` method can
be used:
```js
const element = document.querySelector(`#${CSS.escape(id)} > img`);
```
The `escape()` method can also be used for escaping strings, although it
escapes characters that don't strictly need to be escaped:
```js
const element = document.querySelector(`a[href="#${CSS.escape(fragment)}"]`);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("CSS")}} interface where this static method resides.
- [A polyfill for the CSS.escape](https://github.com/mathiasbynens/CSS.escape/blob/master/css.escape.js)
| 0 |
data/mdn-content/files/en-us/web/api/css | data/mdn-content/files/en-us/web/api/css/registerproperty_static/index.md | ---
title: "CSS: registerProperty() static method"
short-title: registerProperty()
slug: Web/API/CSS/registerProperty_static
page-type: web-api-static-method
browser-compat: api.CSS.registerProperty_static
---
{{APIRef("CSSOM")}}
The **`CSS.registerProperty()`** static method registers
{{cssxref('--*', 'custom properties')}}, allowing for property type checking, default
values, and properties that do or do not inherit their value.
Registering a custom property allows you to tell the browser how the custom property
should behave; what types are allowed, whether the custom property inherits its value,
and what the default value of the custom property is.
## Syntax
```js-nolint
CSS.registerProperty(PropertyDefinition)
```
### Parameters
A `PropertyDefinition` dictionary object, which can contain the following
members:
- `name`
- : A string representing the
name of the property being defined.
- `syntax` {{optional_inline}}
- : A string representing
the expected syntax of the defined property. Defaults to `"*"`.
- `inherits`
- : A boolean value defining whether the defined property should be inherited
(`true`), or not (`false`). Defaults to `false`.
- `initialValue` {{optional_inline}}
- : A string representing
the initial value of the defined property.
### Return value
`undefined`.
### Exceptions
- `InvalidModificationError` {{domxref("DOMException")}}
- : The given `name` has already been registered.
- `SyntaxError` {{domxref("DOMException")}}
- : The given `name` isn't a valid custom property name (starts with two
dashes, e.g. `--foo`).
- {{jsxref("TypeError")}}
- : The required `name` and/or `inherits` dictionary members were
not provided.
## Examples
The following will register a {{cssxref('--*', 'custom property')}},
`--my-color`, using `registerProperty()`, as a color, give it a
default value, and have it not inherit its value:
```js
window.CSS.registerProperty({
name: "--my-color",
syntax: "<color>",
inherits: false,
initialValue: "#c0ffee",
});
```
In this example, the custom property `--my-color` has been registered using
the syntax `<color>`. We can now use that property to transition a
gradient on hover or focus. Notice that with the registered property the transition
works, but that it doesn't with the unregistered property!
```css
.registered {
--my-color: #c0ffee;
background-image: linear-gradient(to right, #fff, var(--my-color));
transition: --my-color 1s ease-in-out;
}
.registered:hover,
.registered:focus {
--my-color: #b4d455;
}
.unregistered {
--unregistered: #c0ffee;
background-image: linear-gradient(to right, #fff, var(--unregistered));
transition: --unregistered 1s ease-in-out;
}
.unregistered:hover,
.unregistered:focus {
--unregistered: #b4d455;
}
button {
font-size: 3vw;
}
```
We can add these styles to some buttons:
```html
<button class="registered">Background Registered</button>
<button class="unregistered">Background Not Registered</button>
```
{{EmbedLiveSample("Examples", 320, 320)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the CSS properties and values API](/en-US/docs/Web/API/CSS_Properties_and_Values_API/guide)
- {{DOMxRef("CSS")}}
- {{DOMxRef("CSS/supports_static", "CSS.supports()")}}
- {{DOMxRef("CSS/escape_static", "CSS.escape()")}}
- {{DOMxRef("CSS/factory_functions_static", 'CSS factory functions')}}
- CSS {{cssxref("@property")}}
| 0 |
data/mdn-content/files/en-us/web/api/css | data/mdn-content/files/en-us/web/api/css/factory_functions_static/index.md | ---
title: CSS numeric factory functions
slug: Web/API/CSS/factory_functions_static
page-type: web-api-static-method
browser-compat: api.CSS
---
{{APIRef("CSSOM")}}
The **CSS numeric factory
functions**, such as `CSS.em()` and
`CSS.turn()` are methods that return [CSSUnitValues](/en-US/docs/Web/API/CSSUnitValue) with the value being
the numeric argument and the unit being the name of the method used. These
functions create new numeric values less verbosely than using the
{{domxref("CSSUnitValue.CSSUnitValue", "CSSUnitValue()")}} constructor.
## Syntax
```js-nolint
CSS.number(number)
CSS.percent(number)
// <length>
CSS.em(number)
CSS.ex(number)
CSS.ch(number)
CSS.ic(number)
CSS.rem(number)
CSS.lh(number)
CSS.rlh(number)
CSS.vw(number)
CSS.vh(number)
CSS.vi(number)
CSS.vb(number)
CSS.vmin(number)
CSS.vmax(number)
CSS.cm(number)
CSS.mm(number)
CSS.Q(number)
CSS.in(number)
CSS.pt(number)
CSS.pc(number)
CSS.px(number)
// <angle>
CSS.deg(number)
CSS.grad(number)
CSS.rad(number)
CSS.turn(number)
// <time>
CSS.s(number)
CSS.ms(number)
// <frequency>
CSS.Hz(number)
CSS.kHz(number)
// <resolution>
CSS.dpi(number)
CSS.dpcm(number)
CSS.dppx(number)
// <flex>
CSS.fr(number)
```
## Examples
We use the `CSS.vmax()` numeric factory function to create a
{{domxref('CSSUnitValue')}}:
```js
const height = CSS.vmax(50);
console.log(height); // CSSUnitValue {value: 50, unit: "vmax"}
console.log(height.value); // 50
console.log(height.unit); // vmax
```
In this example, we set the margin on our element using the `CSS.px()`
factory function:
```js
myElement.attributeStyleMap.set("margin", CSS.px(40));
const currentMargin = myElement.attributeStyleMap.get("margin");
console.log(currentMargin.value, currentMargin.unit); // 40, 'px'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CSSUnitValue.CSSUnitValue", "CSSUnitValue()")}}
| 0 |
data/mdn-content/files/en-us/web/api/css | data/mdn-content/files/en-us/web/api/css/supports_static/index.md | ---
title: "CSS: supports() static method"
short-title: supports()
slug: Web/API/CSS/supports_static
page-type: web-api-static-method
browser-compat: api.CSS.supports_static
---
{{APIRef("CSSOM")}}
The **`CSS.supports()`** static method returns a boolean value
indicating if the browser supports a given CSS feature, or not.
## Syntax
```js-nolint
CSS.supports(propertyName, value)
CSS.supports(supportCondition)
```
### Parameters
There are two distinct sets of parameters. The first one allows to test the support of
a pair _property-value_:
- `propertyName`
- : A string containing the name of the CSS property to check.
- `value`
- : A string containing the value of the CSS property to check.
The second syntax takes one parameter matching the condition of
{{cssxref("@supports")}}:
- `supportCondition`
- : A string containing the condition to check.
### Return value
`true` if the browser supports the rule, otherwise `false`.
## Examples
```js
result = CSS.supports("text-decoration-style", "blink");
result = CSS.supports("display: flex");
result = CSS.supports("(--foo: red)");
result = CSS.supports(
"(transform-style: preserve) or (-moz-transform-style: preserve) or (-webkit-transform-style: preserve)",
);
// result is true or false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{cssxref("@supports")}} at-rule that allows for the same functionality but in a
declarative way.
- The {{domxref("CSSSupportsRule")}} CSSOM class allowing to manipulate
{{cssxref("@supports")}} at-rules.
| 0 |
data/mdn-content/files/en-us/web/api/css | data/mdn-content/files/en-us/web/api/css/paintworklet_static/index.md | ---
title: "CSS: paintWorklet static property"
short-title: paintWorklet
slug: Web/API/CSS/paintWorklet_static
page-type: web-api-static-property
status:
- experimental
browser-compat: api.CSS.paintWorklet_static
---
{{APIRef("CSSOM")}}{{SeeCompatTable}}{{SecureContext_Header}}
The static, read-only **`paintWorklet`** property of the {{DOMxRef("CSS")}} interface provides access to the
paint [worklet](/en-US/docs/Web/API/Worklet), which programmatically generates an image where a CSS
property expects a file.
## Value
The associated {{DOMxRef('Worklet')}} object.
## Examples
The following example demonstrates loading a paint [worklet](/en-US/docs/Web/API/Worklet) from its js
file and does so by feature detection.
```js
if ("paintWorklet" in CSS) {
CSS.paintWorklet.addModule("checkerboard.js");
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API)
- [Houdini APIs](/en-US/docs/Web/API/Houdini_APIs)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/editcontext/index.md | ---
title: EditContext
slug: Web/API/EditContext
page-type: web-api-interface
status:
- experimental
browser-compat: api.EditContext
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`EditContext`** interface represents the text edit context of an element that was made editable by using the {{domxref("EditContext API", "", "", "nocode")}}.
The {{domxref("EditContext API", "", "", "nocode")}} can be used to build rich text editors on the web that support advanced text input experiences, such as {{glossary("Input Method Editor")}} (IME) composition, emoji picker, or any other platform-specific editing-related UI surfaces.
## Constructor
- {{domxref("EditContext.EditContext", "EditContext()")}} {{experimental_inline}}
- : Returns a new `EditContext` instance.
## Instance properties
- {{domxref("EditContext.text")}} {{ReadOnlyInline}} {{experimental_inline}}
- : The editable content of the element.
- {{domxref("EditContext.selectionStart")}} {{ReadOnlyInline}} {{experimental_inline}}
- : The offset, within the editable text content, of the start of the current selection.
- {{domxref("EditContext.selectionEnd")}} {{ReadOnlyInline}} {{experimental_inline}}
- : The offset, within the editable text content, of the end of the current selection.
- {{domxref("EditContext.characterBoundsRangeStart")}} {{ReadOnlyInline}} {{experimental_inline}}
- : The offset, within the editable text content, where the last IME composition started.
## Instance methods
_`EditContext` is based on the {{domxref("EventTarget")}} interface, and includes its methods._
- {{domxref("EditContext.attachedElements()")}} {{experimental_inline}}
- : An {{jsxref("Array")}} containing one {{domxref("HTMLElement")}} object which is the element that's associated with the `EditContext` object.
- {{domxref("EditContext.characterBounds()")}} {{experimental_inline}}
- : The list of bounding rectangles for the characters in the `EditContext` object.
- {{domxref("EditContext.updateText()")}} {{experimental_inline}}
- : Updates the internal text content of the `EditContext` object.
- {{domxref("EditContext.updateSelection()")}} {{experimental_inline}}
- : Updates the internal state of the selection within the editable text context.
- {{domxref("EditContext.updateControlBounds()")}} {{experimental_inline}}
- : Informs the operating system about the position and size of the editable text region.
- {{domxref("EditContext.updateSelectionBounds()")}} {{experimental_inline}}
- : Informs the operating system about the position and size of the selection within the editable text region.
- {{domxref("EditContext.updateCharacterBounds()")}} {{experimental_inline}}
- : Informs the operating system about the position and size of the characters in the `EditContext` object.
## Events
- {{domxref("EditContext.textupdate_event", "textupdate")}} {{experimental_inline}}
- : Fired when the user has made changes to the text or selection.
- {{domxref("EditContext.textformatupdate_event", "textformatupdate")}} {{experimental_inline}}
- : Fired when composition using an {{glossary("Input Method Editor")}} (IME) window is happening and the IME decides that certain parts of the text being composed should be formatted differently to indicate the composition state.
- {{domxref("EditContext.characterboundsupdate_event", "characterboundsupdate")}} {{experimental_inline}}
- : Fired when the operating system needs to know the size and position of certain characters within the editable text region of the `EditContext` object, in order to display an IME window.
- {{domxref("EditContext.compositionstart_event", "compositionstart")}} {{experimental_inline}}
- : Fired when composition using an IME window is starting.
- {{domxref("EditContext.compositionend_event", "compositionend")}} {{experimental_inline}}
- : Fired when composition using an IME window is ending.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/updateselectionbounds/index.md | ---
title: "EditContext: updateSelectionBounds() method"
short-title: updateSelectionBounds()
slug: Web/API/EditContext/updateSelectionBounds
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.EditContext.updateSelectionBounds
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`EditContext.updateSelectionBounds()`** method of the {{domxref("EditContext")}} interface is used to inform the operating system about the bounds of the text selection within the editable region that's associated with the `EditContext` object.
Call this method to tell the operating system the bounds of the user's current selection. You should call the method whenever the user's selection changes in the editable region. The selection bounds are used by the operating system to help position the IME window or any other platform-specific editing-related UI surfaces.
## Syntax
```js-nolint
updateSelectionBounds(selectionBounds)
```
### Parameters
- `selectionBounds`
- : A {{domxref("DOMRect")}} object representing the new selection bounds.
### Exceptions
- If no argument is provided, a `TypeError` {{domxref("DOMException")}} is thrown.
- If the provided argument is not a {{domxref("DOMRect")}} a `TypeError` {{domxref("DOMException")}} is thrown.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("EditContext")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/compositionend_event/index.md | ---
title: "EditContext: compositionend event"
short-title: compositionend
slug: Web/API/EditContext/compositionend_event
page-type: web-api-event
status:
- experimental
browser-compat: api.EditContext.compositionend_event
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The `compositionend` event of the {{domxref("EditContext")}} interface fires when composition using a {{glossary("Input Method Editor")}} (IME) window ends.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("compositionend", (event) => {});
oncompositionend = (event) => {};
```
## Examples
### Using `compositionend` to change the editable region's border
In the following example, the editable region's border is set to red when the `compositionstart` event fires, and back to black when the `compositionend` event fires. Note that the event listener callbacks in this example are only called when using an IME window, or other platform-specific editing UI surfaces, to compose text.
```css
#text-editor {
border: 1px solid black;
}
#text-editor.is-composing {
border-color: red;
}
```
```html
<div id="text-editor"></div>
```
```js
const editorElement = document.getElementById("text-editor");
const editContext = new EditContext();
editorElement.editContext = editContext;
editContext.addEventListener("compositionstart", (event) => {
editorElement.classList.add("is-composing");
});
editContext.addEventListener("compositionend", (event) => {
editorElement.classList.remove("is-composing");
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/textformatupdate_event/index.md | ---
title: "EditContext: textformatupdate event"
short-title: textformatupdate
slug: Web/API/EditContext/textformatupdate_event
page-type: web-api-event
status:
- experimental
browser-compat: api.EditContext.textformatupdate_event
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The `textformatupdate` event of the {{domxref("EditContext")}} interface fires when composition using a {{glossary("Input Method Editor")}} (IME) window is happening.
The event is fired when the IME decides that certain parts of the text being composed should be formatted differently to indicate the composition state.
The following screenshot shows an example of text being written in the Nodepad app on Windows, by using the Japanese IME. The text is formatted with a thick underline to indicate that it's been composed from one of the IME's suggestions.

As a web developer, you should listen for the `textformatupdate` event and update the formatting of the text displayed in your editable region accordingly.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("textformatupdate", (event) => {});
ontextformatupdate = (event) => {};
```
## Event type
A {{domxref("TextFormatUpdateEvent")}}. Inherits from {{domxref("Event")}}.
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref('TextFormatUpdateEvent.getTextFormats')}}
- : Returns the list of text formats that the IME window wants to apply to the text.
## Examples
### Rendering IME composition text formatting
In the following example, the `textformatupdate` event is used to update the formatting of the text in the editable region. Note that the event listener callback in this example is only called when using an IME window, or other platform-specific editing UI surfaces, to compose text.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const TEXT_X = 10;
const TEXT_Y = 10;
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
const editContext = new EditContext();
canvas.editContext = editContext;
editContext.addEventListener("textformatupdate", (e) => {
// Clear the canvas.
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Render the text.
ctx.fillText(editContext.text, TEXT_X, TEXT_Y);
// Get the text formats that the IME window wants to apply.
const formats = e.getTextFormats();
// Iterate over the text formats
for (const format of formats) {
const { rangeStart, rangeEnd, underlineStyle, underlineThickness } = format;
const underlineXStart = ctx.measureText(
editContext.text.substring(0, rangeStart),
).width;
const underlineXEnd = ctx.measureText(
editContext.text.substring(0, rangeEnd),
).width;
const underlineY = TEXT_Y + 3;
// For brevity, this example only draws a simple underline.
// You should use the underlineStyle and underlineThickness values to draw the underline.
ctx.beginPath();
ctx.moveTo(TEXT_X + underlineXStart, underlineY);
ctx.lineTo(TEXT_X + underlineXEnd, underlineY);
ctx.stroke();
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/updatecharacterbounds/index.md | ---
title: "EditContext: updateCharacterBounds() method"
short-title: updateCharacterBounds()
slug: Web/API/EditContext/updateCharacterBounds
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.EditContext.updateCharacterBounds
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`EditContext.updateCharacterBounds()`** method of the {{domxref("EditContext")}} interface should be called as response to a {{domxref("EditContext.characterboundsupdate_event", "characterboundsupdate")}} event to inform the operating system about the position and size of the characters in the `EditContext` object.
The `characterboundsupdate` event is the only time you need to call the `updateCharacterBounds()` method.
The character bounds information is then used by the operating system to correctly position the {{glossary("Input Method Editor")}} (IME) window when needed. This is especially important in situations where the operating system can't automatically detect the position and size of the characters, such as when rendering text in a `<canvas>` element.
### Avoid sudden jumps in the IME window position
Calculating the character bounds and calling `updateCharacterBounds` synchronously, within the `characterboundsupdate` event ensures that the operating system has the information it needs when it displays the IME window. If you don't call `updateCharacterBounds()` synchronously within the event handler, users may observe the IME window being displayed in the wrong position before being moved to the correct position.
### Which characters to include
The `updateCharacterBounds()` method should only be called when the operating system indicates that it requires the information, and only for the characters that are included in the current IME composition.
The event object passed to the `characterboundsupdate` event handler contains a `rangeStart` and `rangeEnd` properties that indicate the range of characters that are currently being composed. The `updateCharacterBounds()` method should only be called for the characters in this range.
## Syntax
```js-nolint
updateCharacterBounds(rangeStart, characterBounds)
```
### Parameters
- `rangeStart`
- : A number representing the start of the range of text for which character bounds are provided.
- `characterBounds`
- : An {{jsxref("Array")}} containing {{domxref("DOMRect")}} objects representing the character bounds.
### Exceptions
- If less than two arguments are provided, a `TypeError` {{domxref("DOMException")}} is thrown.
- if `rangeStart` is not a number or `characterBounds` is not iterable, a `TypeError` {{domxref("DOMException")}} is thrown.
## Examples
### Updating the character bounds when needed
This example shows how to use the `updateCharacterBounds` method to update the character bounds in the `EditContext` of a `<canvas>` element when the operating system indicates that it requires the information. Note that the `characterboundsupdate` event listener callback in this example is only called when using an IME window, or other platform-specific editing UI surfaces, to compose text.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const FONT_SIZE = 40;
const FONT = `${FONT_SIZE}px Arial`;
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
ctx.font = FONT;
const editContext = new EditContext();
canvas.editContext = editContext;
function computeCharacterBound(offset) {
// Measure the width from the start of the text to the character.
const widthBeforeChar = ctx.measureText(
editContext.text.substring(0, offset),
).width;
// Measure the character width.
const charWidth = ctx.measureText(editContext.text[offset]).width;
const charX = canvas.offsetLeft + widthBeforeChar;
const charY = canvas.offsetTop;
// Return a DOMRect representing the character bounds.
return DOMRect.fromRect({
x: charX,
y: charY - FONT_SIZE,
width: charWidth,
height: FONT_SIZE,
});
}
editContext.addEventListener("characterboundsupdate", (e) => {
const charBounds = [];
for (let offset = e.rangeStart; offset < e.rangeEnd; offset++) {
charBounds.push(computeCharacterBound(offset));
}
editContext.updateCharacterBounds(e.rangeStart, charBounds);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("EditContext")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/textupdate_event/index.md | ---
title: "EditContext: textupdate event"
short-title: textupdate
slug: Web/API/EditContext/textupdate_event
page-type: web-api-event
status:
- experimental
browser-compat: api.EditContext.textupdate_event
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The `textupdate` event of the {{domxref("EditContext")}} interface fires when the user has made changes to the text or selection of an editable region that's attached to an `EditContext` instance.
This event makes it possible to render the updated text and selection in the UI, in response to user input.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("textupdate", (event) => {});
ontextupdate = (event) => {};
```
## Event type
A {{domxref("TextUpdateEvent")}}. Inherits from {{domxref("Event")}}.
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref('TextUpdateEvent.updateRangeStart')}} {{readonlyinline}}
- : Returns the index of the first character in the range of text that was updated.
- {{domxref('TextUpdateEvent.updateRangeEnd')}} {{readonlyinline}}
- : Returns the index of the last character in the range of text that was updated.
- {{domxref('TextUpdateEvent.text')}} {{readonlyinline}}
- : Returns the text that was inserted in the updated range.
- {{domxref('TextUpdateEvent.selectionStart')}} {{readonlyinline}}
- : Returns the index of the first character in the new selection range, after the update.
- {{domxref('TextUpdateEvent.selectionEnd')}} {{readonlyinline}}
- : Returns the index of the last character in the new selection range, after the update.
## Examples
### Rendering the updated text on `textupdate`
In the following example, the `textupdate` event of the EditContext API is used to render the text a user enters in an editable `<canvas>` element.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
const editContext = new EditContext();
canvas.editContext = editContext;
editContext.addEventListener("textupdate", (e) => {
// When the user has focus on the <canvas> and enters text,
// this event is fired, and we use it to re-render the text.
console.log(
`The user entered the text: ${e.text} at ${e.updateRangeStart}. Re-rendering the full EditContext text`,
);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillText(editContext.text, 10, 10);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/compositionstart_event/index.md | ---
title: "EditContext: compositionstart event"
short-title: compositionstart
slug: Web/API/EditContext/compositionstart_event
page-type: web-api-event
status:
- experimental
browser-compat: api.EditContext.compositionstart_event
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The `compositionstart` event of the {{domxref("EditContext")}} interface fires when composition using a {{glossary("Input Method Editor")}} (IME) window starts.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("compositionstart", (event) => {});
oncompositionstart = (event) => {};
```
## Examples
### Using `compositionstart` to change the editable region's border
In the following example, the editable region's border is set to red when the `compositionstart` event fires, and back to black when the `compositionend` event fires. Note that the event listener callbacks in this example are only called when using an IME window, or other platform-specific editing UI surfaces, to compose text.
```css
#text-editor {
border: 1px solid black;
}
#text-editor.is-composing {
border-color: red;
}
```
```html
<div id="text-editor"></div>
```
```js
const editorElement = document.getElementById("text-editor");
const editContext = new EditContext();
editorElement.editContext = editContext;
editContext.addEventListener("compositionstart", (event) => {
editorElement.classList.add("is-composing");
});
editContext.addEventListener("compositionend", (event) => {
editorElement.classList.remove("is-composing");
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/updatecontrolbounds/index.md | ---
title: "EditContext: updateControlBounds() method"
short-title: updateControlBounds()
slug: Web/API/EditContext/updateControlBounds
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.EditContext.updateControlBounds
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`EditContext.updateControlBounds()`** method of the {{domxref("EditContext")}} interface is used to inform the operating system about the position and size of the editable text region of the `EditContext` object.
Call this method to tell the operating system the bounds of the current editable region. You should call it when initializing the EditContext, and whenever the editable region's bounds change such as when the webpage is resized. These bounds are used to position platform-specific editing-related UI surfaces such as an {{glossary("Input Method Editor")}} (IME) window.
## Syntax
```js-nolint
updateControlBounds(controlBounds)
```
### Parameters
- `controlBounds`
- : A {{domxref("DOMRect")}} object representing the new control bounds.
### Exceptions
- If no argument is provided, a `TypeError` {{domxref("DOMException")}} is thrown.
- If the provided argument is not a {{domxref("DOMRect")}} a `TypeError` {{domxref("DOMException")}} is thrown.
## Examples
### Updating the control bounds when the editor is initialized and on window resize
This example shows how to use the `updateControlBounds()` method to tell the platform where the editable region is at all times.
```css
#editor {
border: 1px solid black;
height: 50vw;
width: 50vh;
}
```
```html
<div id="editor"></div>
```
```js
const editorEl = document.getElementById("editor");
const editContext = new EditContext();
editorEl.editContext = editContext;
function updateControlBounds() {
const editorBounds = editorEl.getBoundingClientRect();
editContext.updateControlBounds(editorBounds);
console.log(
`Updated control bounds to ${editorBounds.x}, ${editorBounds.y}, ${editorBounds.width}, ${editorBounds.height}`,
);
}
// Update the control bounds now.
updateControlBounds();
// And when the page is resized.
window.addEventListener("resize", updateControlBounds);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("EditContext")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/attachedelements/index.md | ---
title: "EditContext: attachedElements() method"
short-title: attachedElements()
slug: Web/API/EditContext/attachedElements
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.EditContext.attachedElements
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`attachedElements()`** method of the {{domxref("EditContext")}} interface returns an {{jsxref("Array")}} that contains only one item. This item is the element that's associated with the `EditContext` object.
## Syntax
```js-nolint
attachedElements()
```
### Return value
An {{jsxref("Array")}} containing one {{domxref("HTMLElement")}} object.
There can only be one element associated to an `EditContext` instance, so the returned array will always contain one element. If the API is extended in the future to support multiple associated elements, the return value will be an array containing multiple elements.
## Examples
### Getting the element associated with an `EditContext` instance
This example shows how to use the `attachedElements` method to get the element that's associated with an `EditContext` instance.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const canvas = document.getElementById("editor-canvas");
const editContext = new EditContext();
canvas.editContext = editContext;
const attachedElements = editContext.attachedElements();
console.log(attachedElements[0] === canvas); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("EditContext")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/text/index.md | ---
title: "EditContext: text property"
short-title: text
slug: Web/API/EditContext/text
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.EditContext.text
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`text`** read-only property of the {{domxref("EditContext")}} interface represents the editable content of the element.
## Value
A string containing the current editable content of the element that's attached to the `EditContext` object. Its initial value is the empty string.
This string may or may not be equal to the value of the {{domxref("Node.textContent", "textContent")}} property of the DOM element that's associated to the `EditContext`. The associated element might, for example, be a `<canvas>` element, which doesn't have a `textContent` property. Or, the associated element might be a `<div>` element that contains text that's different than the `EditContext.text` value, for more advanced rendering.
The `text` property of the `EditContext` object can be used as the model for the editable text region. Other properties of the `EditContext` object, such as `selectionStart` and `selectionEnd` refer to offsets within the `text` string.
## Examples
### Using `text` to render the text in an editable canvas
In the following example, the EditContext API is used to render the text a user enters in a `<canvas>` element.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
const editContext = new EditContext();
canvas.editContext = editContext;
editContext.addEventListener("textupdate", (e) => {
// When the user has focus on the <canvas> and enters text,
// this event is fired, and we use it to re-render the text.
console.log(
`The user entered the text: ${e.text}. Re-rendering the full EditContext text`,
);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillText(editContext.text, 10, 10);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/characterbounds/index.md | ---
title: "EditContext: characterBounds() method"
short-title: characterBounds()
slug: Web/API/EditContext/characterBounds
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.EditContext.characterBounds
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`characterBounds()`** method of the {{domxref("EditContext")}} interface returns an {{jsxref("Array")}} containing the list of bounding rectangles for the characters in the `EditContext` object.
The position and size of the characters in an `EditContext` object is used by the operating system to correctly position platform-specific editing-related UI surfaces such as an {{glossary("Input Method Editor")}} (IME) window when needed. This is especially important in situations where the operating system can't automatically detect the position and size of the characters, such as when rendering text in a `<canvas>` element.
Web developers will most likely be interested in using the {{domxref("EditContext.characterboundsupdate_event", "characterboundsupdate")}} event together with the {{domxref("EditContext.updateCharacterBounds()")}} method to update the character bounds when the operating system indicates that it requires information about the position and size of the characters.
The `characterBounds()` method returns the list of character bounds that were last updated with `updateCharacterBounds()`. The list doesn't contain an item for every character in the `EditContext` object, only for the characters that were updated with `updateCharacterBounds()`. To know where the characters are located in the `EditContext` object, use the {{domxref("EditContext.characterBoundsRangeStart")}} property.
## Syntax
```js-nolint
characterBounds()
```
### Return value
An {{jsxref("Array")}} containing {{domxref("DOMRect")}} objects.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("EditContext")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/updatetext/index.md | ---
title: "EditContext: updateText() method"
short-title: updateText()
slug: Web/API/EditContext/updateText
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.EditContext.updateText
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`updateText()`** method of the {{domxref("EditContext")}} interface updates the internal text content of an `EditContext` object.
This method doesn't need to be used when the user types text in the associated element. The `EditContext` object will automatically update its internal text content, and will fire {{domxref("EditContext.textupdate_event", "textupdate")}} events as needed.
This method can, however, be used when the user interacts with the text content in other ways, such as when pasting text from the clipboard.
## Syntax
```js-nolint
updateText(rangeStart, rangeEnd, text)
```
### Parameters
- `rangeStart`
- : A number representing the start of the range of text to replace.
- `rangeEnd`
- : A number representing the end of the range of text to replace.
- `text`
- : A string representing the new text content.
### Exceptions
- If less than three arguments are provided, a `TypeError` {{domxref("DOMException")}} is thrown.
- if `rangeStart` is greater than `rangeEnd`, a {{domxref("DOMException")}} is thrown.
## Examples
### Updating the editor when the user pastes text in it
This example shows how to use the `updateText` method to update the text content in the `EditContext` of a `<canvas>` element when the user presses the <kbd>Ctrl</kbd>/<kbd>Cmd</kbd> + <kbd>V</kbd> shortcut to paste some text.
The example also uses the {{domxref("Clipboard.readText()")}} method to read the text from the clipboard.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
const editContext = new EditContext();
canvas.editContext = editContext;
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillText(editContext.text, 0, 40);
}
editContext.addEventListener("textupdate", (e) => {
render();
});
canvas.addEventListener("keydown", async (e) => {
if (e.key == "v" && (e.ctrlKey || e.metaKey)) {
const pastedText = await navigator.clipboard.readText();
console.log(
`The user pasted the text: ${pastedText}. Updating the EditContext text.`,
);
editContext.updateText(
editContext.selectionStart,
editContext.selectionEnd,
pastedText,
);
editContext.updateSelection(
editContext.selectionStart + pastedText.length,
editContext.selectionStart + pastedText.length,
);
render();
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("EditContext")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/updateselection/index.md | ---
title: "EditContext: updateSelection() method"
short-title: updateSelection()
slug: Web/API/EditContext/updateSelection
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.EditContext.updateSelection
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`updateSelection()`** method of the {{domxref("EditContext")}} interface updates the internal state of the selection within the editable text context. This method is used to update the selection state when the user interacts with the text rendering in the `EditContext`'s associated element, such as by clicking or dragging the mouse, or by using the keyboard.
## Syntax
```js-nolint
updateSelection(start, end)
```
### Parameters
- `start`
- : A number representing the new selection start.
- `end`
- : A number representing the new selection end.
If the `start` and `end` values are the same, the selection is equivalent to a caret.
### Exceptions
- If only one argument is provided, a `TypeError` {{domxref("DOMException")}} is thrown.
- If either argument is not a positive number, a {{domxref("DOMException")}} is thrown.
- If `start` is greater than `end`, a {{domxref("DOMException")}} is thrown.
## Examples
### Updating the selection when the user interacts with the text
This example shows how to use the `updateSelection` method to update the selection in the `EditContext` of a `canvas` element when the arrow keys are used to move the caret or select text in the editable region.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const canvas = document.getElementById("editor-canvas");
const editContext = new EditContext();
canvas.editContext = editContext;
canvas.addEventListener("keydown", (e) => {
if (e.key == "ArrowLeft") {
const newPosition = Math.max(editContext.selectionStart - 1, 0);
if (e.shiftKey) {
editContext.updateSelection(newPosition, editContext.selectionEnd);
} else {
editContext.updateSelection(newPosition, newPosition);
}
} else if (e.key == "ArrowRight") {
const newPosition = Math.min(
editContext.selectionEnd + 1,
editContext.text.length,
);
if (e.shiftKey) {
editContext.updateSelection(editContext.selectionStart, newPosition);
} else {
editContext.updateSelection(newPosition, newPosition);
}
}
console.log(
`The new EditContext selection is ${editContext.selectionStart}, ${editContext.selectionEnd}`,
);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("EditContext")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/selectionend/index.md | ---
title: "EditContext: selectionEnd property"
short-title: selectionEnd
slug: Web/API/EditContext/selectionEnd
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.EditContext.selectionEnd
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`selectionEnd`** read-only property of the {{domxref("EditContext")}} refers to the offset, within the editable text content, of the end of the current selection.
## Value
A {{jsxref("Number")}}
## Examples
### Using `selectionEnd` to render the user selection in an editable canvas
This example shows how to use the `selectionStart` and `selectionEnd` properties to draw the current selection in a `<canvas>` element that's associated to an `EditContext`.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const ANCHOR_X = 10;
const ANCHOR_Y = 30;
const FONT_SIZE = 20;
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
ctx.font = `${FONT_SIZE}px Arial`;
const editContext = new EditContext({
text: "Hello world!",
selectionStart: 6,
selectionEnd: 11,
});
canvas.editContext = editContext;
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Render the entire text content first.
ctx.fillStyle = "black";
ctx.fillText(editContext.text, ANCHOR_X, ANCHOR_Y);
// Get the width from the start of the text to the start of the selection.
const selectionStartX = ctx.measureText(
editContext.text.substring(0, editContext.selectionStart),
);
// Get the width of the selection.
const selectionWidth = ctx.measureText(
editContext.text.substring(
editContext.selectionStart,
editContext.selectionEnd,
),
);
// Draw a rectangle on top of the text to represent the selection.
ctx.fillStyle = "blue";
ctx.fillRect(
selectionStartX.width + ANCHOR_X,
ANCHOR_Y - FONT_SIZE,
selectionWidth.width,
FONT_SIZE,
);
// Re-render just the selected text in white, over the rectangle.
ctx.fillStyle = "white";
ctx.fillText(
editContext.text.substring(
editContext.selectionStart,
editContext.selectionEnd,
),
selectionStartX.width + ANCHOR_X,
ANCHOR_Y,
);
}
render();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/editcontext/index.md | ---
title: "EditContext: EditContext() constructor"
short-title: EditContext()
slug: Web/API/EditContext/EditContext
page-type: web-api-constructor
status:
- experimental
browser-compat: api.EditContext.EditContext
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`EditContext()`** constructor returns a new {{DOMxRef("EditContext")}} object.
## Syntax
```js-nolint
new EditContext()
new EditContext(options)
```
### Parameters
- `options` {{optional_inline}}
- : An optional object with the following properties:
- `text`
- : A string to set the initial text of the `EditContext`.
- `selectionStart`
- : A number to set the initial selection start of the `EditContext`.
- `selectionEnd`
- : A number to set the initial selection end of the `EditContext`.
## Examples
### Instantiating an `EditContext` object
The following example creates a new `EditContext` object with the initial text "Hello world!" and the initial selection covering the entire text.
```html
<div id="editor"></div>
```
```js
const initialText = "Hello world!";
const editContext = new EditContext({
text: initialText,
selectionStart: 0,
selectionEnd: initialText.length,
});
const editorElement = document.getElementById("editor");
editorElement.editContext = editContext;
console.log(
`EditContext object ready. Text: ${editContext.text}. Selection: ${editContext.selectionStart} - ${editContext.selectionEnd}.`,
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{DOMxRef("EditContext")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/characterboundsupdate_event/index.md | ---
title: "EditContext: characterboundsupdate event"
short-title: characterboundsupdate
slug: Web/API/EditContext/characterboundsupdate_event
page-type: web-api-event
status:
- experimental
browser-compat: api.EditContext.characterboundsupdate_event
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The `characterboundsupdate` event fires when the operating system needs to know the bounds of certain characters within editable text region of the `EditContext` object.
This happens when the operating system needs to display a platform-specific editing-related UI surface such as an {{glossary("Input Method Editor")}} (IME) window.
When the `characterboundsupdate` event fires, you should calculate the character bounds for the text, and then call the {{domxref("EditContext.updateCharacterBounds()")}} method to give the operating system the information it needs.
See the documentation of the {{domxref("EditContext.updateCharacterBounds()", "updateCharacterBounds")}} method for more information about when and how to use the `characterboundsupdate` event.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("characterboundsupdate", (event) => {});
oncharacterboundsupdate = (event) => {};
```
## Event type
A {{domxref("CharacterBoundsUpdateEvent")}}. Inherits from {{domxref("Event")}}.
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref('CharacterBoundsUpdateEvent.rangeStart')}} {{readonlyinline}}
- : The offset of the first character within the editable region text for which the operating system needs the bounds.
- {{domxref('CharacterBoundsUpdateEvent.rangeEnd')}} {{readonlyinline}}
- : The offset of the last character within the editable region text for which the operating system needs the bounds.
## Examples
### Updating the character bounds when needed
This example shows how to use the `updateCharacterBounds` method to update the character bounds in the `EditContext` of a `canvas` element when the operating system indicates that it requires the information. Note that the event listener callback is only called when using an IME window, or other platform-specific editing UI surfaces, to compose text.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const FONT_SIZE = 40;
const FONT = `${FONT_SIZE}px Arial`;
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
ctx.font = FONT;
const editContext = new EditContext();
canvas.editContext = editContext;
function computeCharacterBound(offset) {
// Measure the width from the start of the text to the character.
const widthBeforeChar = ctx.measureText(
editContext.text.substring(0, offset),
).width;
// Measure the character width.
const charWidth = ctx.measureText(editContext.text[offset]).width;
const charX = canvas.offsetLeft + widthBeforeChar;
const charY = canvas.offsetTop;
// Return a DOMRect representing the character bounds.
return DOMRect.fromRect({
x: charX,
y: charY - FONT_SIZE,
width: charWidth,
height: FONT_SIZE,
});
}
editContext.addEventListener("characterboundsupdate", (e) => {
const charBounds = [];
for (let offset = e.rangeStart; offset < e.rangeEnd; offset++) {
charBounds.push(computeCharacterBound(offset));
}
console.log("The required character bounds are", charBounds);
editContext.updateCharacterBounds(e.rangeStart, charBounds);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/characterboundsrangestart/index.md | ---
title: "EditContext: characterBoundsRangeStart property"
short-title: characterBoundsRangeStart
slug: Web/API/EditContext/characterBoundsRangeStart
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.EditContext.characterBoundsRangeStart
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`characterBoundsRangeStart`** read-only property of the {{domxref("EditContext")}} interface indicates the index of the character, within the editable text content, that corresponds to the first item in the {{domxref("EditContext.characterBounds()", "characterBounds")}} array.
For example, if the `EditContent` contains the characters `abc`, and if `characterBoundRangeStart` is `1`, the first item in the `characterBounds` array contains the bounds for the character `b`.
## Value
A {{jsxref("Number")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/editcontext | data/mdn-content/files/en-us/web/api/editcontext/selectionstart/index.md | ---
title: "EditContext: selectionStart property"
short-title: selectionStart
slug: Web/API/EditContext/selectionStart
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.EditContext.selectionStart
---
{{APIRef("EditContext API")}}{{SeeCompatTable}}
The **`selectionStart`** read-only property of the {{domxref("EditContext")}} refers to the offset, within the editable text content, of the start of the current selection.
## Value
A {{jsxref("Number")}}
## Examples
### Using `selectionStart` to render the user selection in an editable canvas
This example shows how to use the `selectionStart` and `selectionEnd` properties to draw the current selection in a `<canvas>` element that's associated to an `EditContext`.
```html
<canvas id="editor-canvas"></canvas>
```
```js
const ANCHOR_X = 10;
const ANCHOR_Y = 30;
const FONT_SIZE = 20;
const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");
ctx.font = `${FONT_SIZE}px Arial`;
const editContext = new EditContext({
text: "Hello world!",
selectionStart: 6,
selectionEnd: 11,
});
canvas.editContext = editContext;
function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Render the entire text content first.
ctx.fillStyle = "black";
ctx.fillText(editContext.text, ANCHOR_X, ANCHOR_Y);
// Get the width from the start of the text to the start of the selection.
const selectionStartX = ctx.measureText(
editContext.text.substring(0, editContext.selectionStart),
);
// Get the width of the selection.
const selectionWidth = ctx.measureText(
editContext.text.substring(
editContext.selectionStart,
editContext.selectionEnd,
),
);
// Draw a rectangle on top of the text to represent the selection.
ctx.fillStyle = "blue";
ctx.fillRect(
selectionStartX.width + ANCHOR_X,
ANCHOR_Y - FONT_SIZE,
selectionWidth.width,
FONT_SIZE,
);
// Re-render just the selected text in white, over the rectangle.
ctx.fillStyle = "white";
ctx.fillText(
editContext.text.substring(
editContext.selectionStart,
editContext.selectionEnd,
),
selectionStartX.width + ANCHOR_X,
ANCHOR_Y,
);
}
render();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrray/index.md | ---
title: XRRay
slug: Web/API/XRRay
page-type: web-api-interface
status:
- experimental
browser-compat: api.XRRay
---
{{APIRef("WebXR Device API")}} {{secureContext_header}}{{SeeCompatTable}}
The **`XRRay`** interface of the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) is a geometric ray described by an origin point and a direction vector.
`XRRay` objects can be passed to {{domxref("XRSession.requestHitTestSource()")}} or {{domxref("XRSession.requestHitTestSourceForTransientInput()")}} to perform hit testing.
## Constructor
- {{domxref("XRRay.XRRay", "XRRay()")}} {{Experimental_Inline}}
- : Creates a new `XRRay` object.
## Instance properties
- {{domxref("XRRay.direction")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A {{domxref("DOMPointReadOnly")}} representing the ray's 3-dimensional directional vector.
- {{domxref("XRRay.matrix")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A transform that can be used to position objects along the `XRRay`. This is a 4 by 4 matrix given as a 16 element {{jsxref("Float32Array")}} in column major order.
- {{domxref("XRRay.origin")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A {{domxref("DOMPointReadOnly")}} representing the 3-dimensional point in space that the ray originates from, in meters.
## Instance methods
None.
## Examples
### Using `XRRay` to request a hit test source
The {{domxref("XRSession.requestHitTestSource()")}} method takes an `XRRay` object for its `offsetRay` option. In this example, the hit test source is positioned slightly above the viewer as the application has some UI elements at the bottom while wanting to maintain the perception of a centered cursor.
```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
requiredFeatures: ["local", "hit-test"],
});
let hitTestSource = null;
xrSession
.requestHitTestSource({
space: viewerSpace, // obtained from xrSession.requestReferenceSpace("viewer");
offsetRay: new XRRay({ y: 0.5 }),
})
.then((viewerHitTestSource) => {
hitTestSource = viewerHitTestSource;
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRSession.requestHitTestSource()")}}
- {{domxref("XRHitTestResult")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrray | data/mdn-content/files/en-us/web/api/xrray/origin/index.md | ---
title: "XRRay: origin property"
short-title: origin
slug: Web/API/XRRay/origin
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRRay.origin
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`origin`** property of the {{DOMxRef("XRRay")}} interface is a {{domxref("DOMPointReadOnly")}} representing the 3-dimensional point in space that the ray originates from, in meters.
## Value
A {{domxref("DOMPointReadOnly")}} object.
## Examples
### Using the `origin` property
The `origin` property contains the 3-dimensional point in space that the ray originates from, in meters.
```js
let origin = { x: 10.0, y: 10.0, z: 10.0, w: 1.0 };
let direction = { x: 10.0, y: 0.0, z: 0.0, w: 0.0 };
let ray = new XRRay(origin, direction);
ray.origin;
// returns DOMPointReadOnly {x : 10.0, y : 10.0, z : 10.0, w : 1.0}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMPointReadOnly")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrray | data/mdn-content/files/en-us/web/api/xrray/matrix/index.md | ---
title: "XRRay: matrix property"
short-title: matrix
slug: Web/API/XRRay/matrix
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRRay.matrix
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`matrix`** property of the {{DOMxRef("XRRay")}} interface is a transform that can be used to position objects along the `XRRay`. This is a 4 by 4 matrix given as a 16 element {{jsxref("Float32Array")}} in column major order.
The transform from a ray originates at [0, 0, 0] and extends down the negative z-axis to the ray described by the `XRRay`'s `origin` and `direction`.
## Value
A 16 element {{jsxref("Float32Array")}} object representing a 4 by 4 matrix in column major order.
## Examples
### Using the `matrix` property
The `matrix` property can be used to position graphical representations of the ray when rendering.
```js
let origin = { x: 10.0, y: 10.0, z: 10.0, w: 1.0 };
let direction = { x: 10.0, y: 0.0, z: 0.0, w: 0.0 };
let ray = new XRRay(origin, direction);
// Render the ray using the `ray.matrix` transform
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Float32Array")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrray | data/mdn-content/files/en-us/web/api/xrray/direction/index.md | ---
title: "XRRay: direction property"
short-title: direction
slug: Web/API/XRRay/direction
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRRay.direction
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The _read-only_ **`direction`** property of the {{DOMxRef("XRRay")}} interface is a {{domxref("DOMPointReadOnly")}} representing the ray's 3-dimensional directional vector, normalized to a [unit vector](https://en.wikipedia.org/wiki/Unit_vector) with a length of 1.0.
## Value
A {{domxref("DOMPointReadOnly")}} object.
## Examples
### Using the `direction` property
The `direction` property contains the normalized ray's 3-dimensional directional vector.
```js
let origin = { x: 10.0, y: 10.0, z: 10.0, w: 1.0 };
let direction = { x: 10.0, y: 0.0, z: 0.0, w: 0.0 };
let ray = new XRRay(origin, direction);
ray.direction;
// returns DOMPointReadOnly {x : 1.0, y : 0.0, z : 0.0, w : 0.0}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMPointReadOnly")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrray | data/mdn-content/files/en-us/web/api/xrray/xrray/index.md | ---
title: "XRRay: XRRay() constructor"
short-title: XRRay()
slug: Web/API/XRRay/XRRay
page-type: web-api-constructor
status:
- experimental
browser-compat: api.XRRay.XRRay
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`XRRay()`** constructor creates a new {{domxref("XRRay")}} object which is a geometric ray described by an origin point and a direction vector.
## Syntax
```js-nolint
new XRRay()
new XRRay(origin)
new XRRay(origin, direction)
new XRRay(transform)
```
### Parameters
- `origin` {{Optional_Inline}}
- : A point object defining the 3-dimensional point in space that the ray originates from, in meters. All dimensions are optional, however, if provided, the origin's `w` property must be 1.0. The object is initialized to `{ x: 0.0, y: 0.0, z: 0.0, w: 1.0 }` by default.
- `direction` {{Optional_Inline}}
- : A vector object defining the ray's 3-dimensional directional vector. All dimensions are optional, however, if provided, the direction's `w` property must be 0.0. The object is initialized to: `{ x: 0.0, y: 0.0, z: -1.0, w: 0.0 }` by default.
- `transform` {{Optional_Inline}}
- : An {{domxref("XRRigidTransform")}} object representing the position and orientation of the ray.
### Return value
A newly-created {{domxref("XRRay")}} object.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if one of the following conditions is met:
- all of `direction`'s `x`, `y`, and `z` coordinates are zero.
- `direction`'s `w` coordinate is not 0.0.
- `origin`'s `w` coordinate is not 1.0.
## Examples
### Creating `XRRay` objects
The `XRRay()` constructor allows to creating new rays by either providing an `origin` point and a `direction` vector, or by passing in an {{domxref("XRRigidTransform")}} object.
```js
// Default configuration
let ray1 = new XRRay();
// Specifying origin, leaving direction as default
let ray2 = new XRRay({ y: 0.5 });
// Specifying both, origin and direction
let origin = { x: 10.0, y: 10.0, z: 10.0, w: 1.0 };
let direction = { x: 10.0, y: 0.0, z: 0.0, w: 0.0 };
let ray3 = new XRRay(origin, direction);
// Using DOMPoint.fromPoint
let ray4 = new XRRay(DOMPoint.fromPoint(origin), DOMPoint.fromPoint(direction));
// Using rigid transform
let rigidTransform = new XRRigidTransform(
DOMPoint.fromPoint(origin),
DOMPoint.fromPoint(direction),
);
let ray5 = new XRRay(rigidTransform);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("DOMPoint")}}
- {{domxref("DOMPoint.fromPoint_static", "DOMPoint.fromPoint()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xrrenderstate/index.md | ---
title: XRRenderState
slug: Web/API/XRRenderState
page-type: web-api-interface
status:
- experimental
browser-compat: api.XRRenderState
---
{{securecontext_header}}{{APIRef("WebXR")}}{{SeeCompatTable}}
The **`XRRenderState`** interface of the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) contains configurable values which affect how the imagery generated by an {{DOMxRef("XRSession")}} gets composited. These properties include the range of distances from the viewer within which content should be rendered, the vertical field of view (for inline presentations), and a reference to the {{domxref("XRWebGLLayer")}} being used as the target for rendering the scene prior to it being presented on the XR device's display or displays.
When you apply changes using the `XRSession` method {{domxref("XRSession.updateRenderState", "updateRenderState()")}}, the specified changes take effect after the current animation frame has completed, but before the next one begins.
## Instance properties
- {{DOMxRef("XRRenderState.baseLayer")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The {{DOMxRef("XRWebGLLayer")}} from which the browser's compositing system obtains the image for the XR session.
- {{DOMxRef("XRRenderState.depthFar")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The distance, in meters, of the **far clip plane** from the viewer. The far clip plane is the plane which is parallel to the display beyond which rendering of the scene no longer takes place. This, essentially, specifies the maximum distance the user can see.
- {{DOMxRef("XRRenderState.depthNear")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The distance, in meters, of the **near clip plane** from the viewer. The near clip plane is the plane, parallel to the display, at which rendering of the scene begins. Any closer to the viewer than this, and no portions of the scene are drawn.
- {{DOMxRef("XRRenderState.inlineVerticalFieldOfView")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : The default vertical field of view, defined in radians, to use when the session is in `inline` mode. `null` for all immersive sessions.
- {{DOMxRef("XRRenderState.layers")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : An ordered array containing {{domxref("XRLayer")}} objects that are displayed by the XR compositor.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("XRSession.renderState")}}
- {{DOMxRef("XRSession.updateRenderState()")}}
- {{DOMxRef("XRSystem.requestSession", "navigator.xr.requestSession()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrrenderstate | data/mdn-content/files/en-us/web/api/xrrenderstate/layers/index.md | ---
title: "XRRenderState: layers property"
short-title: layers
slug: Web/API/XRRenderState/layers
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRRenderState.layers
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The read-only **`layers`** property of the {{domxref("XRRenderState")}} interface is an ordered array containing {{domxref("XRLayer")}} objects that are displayed by the XR compositor.
## Value
An ordered array containing {{domxref("XRLayer")}} objects. The order of the layers is "back-to-front".
## Examples
### Getting render state layers
To read the WebXR layers array, use the `layers` property on {{domxref("XRRenderState")}}.
Layers can be set using the {{domxref("XRSession.updateRenderState()")}} method.
```js
const xrSession = navigator.xr.requestSession("immersive-ar", {
optionalFeatures: ["layers"],
});
function onXRSessionStarted(xrSession) {
const glCanvas = document.createElement("canvas");
const gl = glCanvas.getContext("webgl", { xrCompatible: true });
const xrGlBinding = new XRWebGLBinding(xrSession, gl);
const projectionLayer = new XRWebGLLayer(xrSession, gl);
const quadLayer = xrGlBinding.createQuadLayer({
pixelWidth: 1024,
pixelHeight: 1024,
});
xrSession.updateRenderState({
layers: [projectionLayer, quadLayer],
});
xrSession.renderState.layers; // [projectionLayer, quadLayer]
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("XRSession.updateRenderState()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrrenderstate | data/mdn-content/files/en-us/web/api/xrrenderstate/baselayer/index.md | ---
title: "XRRenderState: baseLayer property"
short-title: baseLayer
slug: Web/API/XRRenderState/baseLayer
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRRenderState.baseLayer
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The read-only **`baseLayer`** property of the
{{domxref("XRRenderState")}} interface returns the {{domxref("XRWebGLLayer")}} instance
that is the source of bitmap images and a description of how the image is to be rendered
in the device.
This property is read-only; however, you can indirectly change its
value using {{domxref("XRSession.updateRenderState")}}.
## Value
A {{domxref("XRWebGLLayer")}} object which is used as the source of the world's
contents when rendering each frame of the scene.
See the examples below to see how to use {{domxref("XRSession.updateRenderState",
"updateRenderState()")}} to set the current `XRWebGLLayer` used for rendering
the scene.
## Examples
You can set the `XRWebGLLayer` used for rendering by calling
{{domxref("XRSession.updateRenderState", "updateRenderState()")}}, like this:
```js
let canvas = document.querySelector("canvas");
gl = canvas.getContext("webgl", { xrCompatible: true });
setNewWebGLLayer();
function setNewWebGLLayer(gl) {
if (!gl) {
/* WebGL not available */
return;
}
xrSession.updateRenderState({
baseLayer: new XRWebGLLayer(xrSession, gl),
});
}
```
Here, the canvas obtained in the first line is the canvas into which WebGL is going to
draw. That context is passed into {{domxref("XRWebGLLayer.XRWebGLLayer", "new
XRWebGLLayer()")}} to create an `XRWebGLLayer` which uses the contents of the
WebGL context `gl` as the source of the world's image during presentation.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrrenderstate | data/mdn-content/files/en-us/web/api/xrrenderstate/inlineverticalfieldofview/index.md | ---
title: "XRRenderState: inlineVerticalFieldOfView property"
short-title: inlineVerticalFieldOfView
slug: Web/API/XRRenderState/inlineVerticalFieldOfView
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRRenderState.inlineVerticalFieldOfView
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The read-only **`inlineVerticalFieldOfView`**
property of the {{DOMxRef("XRRenderState")}} interface returns the default vertical
field of view for `"inline"` sessions and `null` for all immersive
sessions.
## Value
A {{JSxRef("Number")}} for `"inline"` sessions, which represents the default
field of view, and `null` for immersive sessions.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("XRSystem.requestSession", "navigator.xr.requestSession()")}}
- {{DOMxRef("XRSystem.isSessionSupported", "navigator.xr.isSessionSupported()")}}
| 0 |
data/mdn-content/files/en-us/web/api/xrrenderstate | data/mdn-content/files/en-us/web/api/xrrenderstate/depthfar/index.md | ---
title: "XRRenderState: depthFar property"
short-title: depthFar
slug: Web/API/XRRenderState/depthFar
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRRenderState.depthFar
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`depthFar`** read-only property of the
{{domxref("XRRenderState")}} interface returns the distance in meters of the far clip
plane from the viewer.
## Value
A {{jsxref("Number")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/xrrenderstate | data/mdn-content/files/en-us/web/api/xrrenderstate/depthnear/index.md | ---
title: "XRRenderState: depthNear property"
short-title: depthNear
slug: Web/API/XRRenderState/depthNear
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.XRRenderState.depthNear
---
{{APIRef("WebXR Device API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`depthNear`** read-only property of the
{{domxref("XRRenderState")}} interface returns the distance in meters of the near clip
plane from the viewer.
## Value
A {{jsxref("Number")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfecompositeelement/index.md | ---
title: SVGFECompositeElement
slug: Web/API/SVGFECompositeElement
page-type: web-api-interface
browser-compat: api.SVGFECompositeElement
---
{{APIRef("SVG")}}
The **`SVGFECompositeElement`** interface corresponds to the {{SVGElement("feComposite")}} element.
{{InheritanceDiagram}}
## Constants
<table class="no-markdown">
<tbody>
<tr>
<th>Name</th>
<th>Value</th>
<th>Description</th>
</tr>
<tr>
<td><code>SVG_FECOMPOSITE_OPERATOR_UNKNOWN</code></td>
<td>0</td>
<td>
The type is not one of predefined types. It is invalid to attempt to
define a new value of this type or to attempt to switch an existing
value to this type.
</td>
</tr>
<tr>
<td><code>SVG_FECOMPOSITE_OPERATOR_OVER</code></td>
<td>1</td>
<td>Corresponds to the <code>over</code> value.</td>
</tr>
<tr>
<td><code>SVG_FECOMPOSITE_OPERATOR_IN</code></td>
<td>2</td>
<td>Corresponds to the <code>in</code> value.</td>
</tr>
<tr>
<td><code>SVG_FECOMPOSITE_OPERATOR_OUT</code></td>
<td>3</td>
<td>Corresponds to <code>out</code> value.</td>
</tr>
<tr>
<td><code>SVG_FECOMPOSITE_OPERATOR_ATOP</code></td>
<td>4</td>
<td>Corresponds to <code>atop</code> value.</td>
</tr>
<tr>
<td><code>SVG_FECOMPOSITE_OPERATOR_XOR</code></td>
<td>5</td>
<td>Corresponds to <code>xor</code> value.</td>
</tr>
<tr>
<td><code>SVG_FECOMPOSITE_OPERATOR_ARITHMETIC</code></td>
<td>6</td>
<td>Corresponds to <code>arithmetic</code> value.</td>
</tr>
</tbody>
</table>
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
- {{domxref("SVGFECompositeElement.height")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element.
- {{domxref("SVGFECompositeElement.in1")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element.
- {{domxref("SVGFECompositeElement.result")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element.
- {{domxref("SVGFECompositeElement.type")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedEnumeration")}} corresponding to the {{SVGAttr("type")}} attribute of the given element. It takes one of the `SVG_FECOMPOSITE_OPERATOR_*` constants defined on this interface.
- {{domxref("SVGFECompositeElement.values")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedNumberList")}} corresponding to the {{SVGAttr("values")}} attribute of the given element.
- {{domxref("SVGFECompositeElement.width")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element.
- {{domxref("SVGFECompositeElement.x")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element.
- {{domxref("SVGFECompositeElement.y")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("y")}} attribute of the given element.
## Instance methods
_This interface does not provide any specific methods, but implements those of its parent, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("feComposite")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/imagedecoder/index.md | ---
title: ImageDecoder
slug: Web/API/ImageDecoder
page-type: web-api-interface
status:
- experimental
browser-compat: api.ImageDecoder
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`ImageDecoder`** interface of the {{domxref('WebCodecs API','','','true')}} provides a way to unpack and decode encoded image data.
## Constructor
- {{domxref("ImageDecoder.ImageDecoder", "ImageDecoder()")}} {{Experimental_Inline}}
- : Creates a new `ImageDecoder` object.
## Instance properties
- {{domxref("ImageDecoder.complete")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a boolean value indicating whether encoded data is completely buffered.
- {{domxref("ImageDecoder.completed")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{jsxref("Promise")}} that resolves once `complete` is true.
- {{domxref("ImageDecoder.tracks")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns an {{domxref("ImageTrackList")}} object listing the available tracks and providing a method for selecting a track to decode.
- {{domxref("ImageDecoder.type")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a string reflecting the [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) configured during construction.
## Static methods
- {{domxref("ImageDecoder.isTypeSupported_static", "ImageDecoder.isTypeSupported()")}} {{Experimental_Inline}}
- : Indicates if the provided [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) is supported for unpacking and decoding.
## Instance methods
- {{domxref("ImageDecoder.close()")}} {{Experimental_Inline}}
- : Ends all pending work and releases system resources.
- {{domxref("ImageDecoder.decode()")}} {{Experimental_Inline}}
- : Enqueues a control message to decode the frame of an image.
- {{domxref("ImageDecoder.reset()")}} {{Experimental_Inline}}
- : Aborts all pending `decode()` operations.
## Examples
Given a {{HTMLElement("canvas")}} element:
```html
<canvas></canvas>
```
the following code decodes and renders an animated image to that canvas:
```js
let imageDecoder = null;
let imageIndex = 0;
function renderImage(result) {
const canvas = document.querySelector("canvas");
const canvasContext = canvas.getContext("2d");
canvasContext.drawImage(result.image, 0, 0);
const track = imageDecoder.tracks.selectedTrack;
// We check complete here since `frameCount` won't be stable until all
// data has been received. This may cause us to receive a RangeError
// during the decode() call below which needs to be handled.
if (imageDecoder.complete) {
if (track.frameCount === 1) return;
if (imageIndex + 1 >= track.frameCount) imageIndex = 0;
}
// Decode the next frame ahead of display so it's ready in time.
imageDecoder
.decode({ frameIndex: ++imageIndex })
.then((nextResult) =>
setTimeout(() => {
renderImage(nextResult);
}, result.image.duration / 1000.0),
)
.catch((e) => {
// We can end up requesting an imageIndex past the end since
// we're using a ReadableStream from fetch(), when this happens
// just wrap around.
if (e instanceof RangeError) {
imageIndex = 0;
imageDecoder.decode({ frameIndex: imageIndex }).then(renderImage);
} else {
throw e;
}
});
}
function decodeImage(imageByteStream) {
imageDecoder = new ImageDecoder({ data: imageByteStream, type: "image/gif" });
imageDecoder.decode({ frameIndex: imageIndex }).then(renderImage);
}
fetch("fancy.gif").then((response) => decodeImage(response.body));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/imagedecoder | data/mdn-content/files/en-us/web/api/imagedecoder/completed/index.md | ---
title: "ImageDecoder: completed property"
short-title: completed
slug: Web/API/ImageDecoder/completed
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ImageDecoder.completed
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`completed`** read-only property of the {{domxref("ImageDecoder")}} interface returns a promise that resolves once encoded data has finished buffering.
## Value
A {{jsxref("Promise")}} that resolves with {{jsxref("undefined")}} once {{domxref("ImageDecoder.complete")}} is `true`.
## Examples
In the following example the value of `completed` will be `undefined` once the promise resolves.
```js
let completed = await imageDecoder.completed;
console.log(completed);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/imagedecoder | data/mdn-content/files/en-us/web/api/imagedecoder/istypesupported_static/index.md | ---
title: "ImageDecoder: isTypeSupported() static method"
short-title: isTypeSupported()
slug: Web/API/ImageDecoder/isTypeSupported_static
page-type: web-api-static-method
status:
- experimental
browser-compat: api.ImageDecoder.isTypeSupported_static
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`ImageDecoder.isTypeSupported()`** static method checks if a given [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) can be decoded by the user agent.
## Syntax
```js-nolint
ImageDecoder.isTypeSupported(type)
```
### Parameters
- `type`
- : A string containing the [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) to check for decoding support.
### Return value
A {{jsxref("promise")}} that resolves with a boolean value indicating whether images with a format of `type` can be decoded by the API.
## Examples
The following example checks if GIF and PCX images are supported for decoding and prints the result to the console.
```js
let isGifSupported = await ImageDecoder.isTypeSupported("image/gif");
console.log(`GIF supported: ${isGifSupported}`); // Likely true.
let isPcxSupported = await ImageDecoder.isTypeSupported("image/pcx");
console.log(`PCX supported: ${isPcxSupported}`); // Probably false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/imagedecoder | data/mdn-content/files/en-us/web/api/imagedecoder/decode/index.md | ---
title: "ImageDecoder: decode() method"
short-title: decode()
slug: Web/API/ImageDecoder/decode
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.ImageDecoder.decode
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`decode()`** method of the {{domxref("ImageDecoder")}} interface enqueues a control message to decode the frame of an image.
## Syntax
```js-nolint
decode()
decode(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object containing the following members:
- `frameIndex` {{optional_inline}}
- : An integer representing the index of the frame to decode. Defaults to `0` (the first frame).
- `completeFramesOnly` {{optional_inline}}
- : A {{jsxref("boolean")}} defaulting to `true`. When `false` indicates that for progressive images the decoder may output an image with reduced detail. When `false`, the promise returned by `decode()` will resolve exactly once for each new level of detail.
### Return value
A {{jsxref("promise")}} that resolves with an object containing the following members:
- `image`
- : A {{domxref("VideoFrame")}} containing the decoded image.
- `complete`
- : A {{jsxref("boolean")}}, if `true` indicates that `image` contains the final full-detail output.
### Exceptions
If an error occurs, the promise will resolve with following exception:
- `InvalidStateError` {{domxref("DOMException")}}
- : Returned if any of the following conditions apply:
- `close` is true, meaning {{domxref("ImageDecoder.close()","close()")}} has already been called.
- The requested frame does not exist.
## Examples
### Synchronous decoding of a completed image frame
The following example decodes the second frame (at index `1`) and prints the resulting {{domxref("VideoFrame")}} to the console.
```js
let result = await imageDecoder.decode({ frameIndex: 1 });
console.log(result.image);
```
### Partial decoding of a progressive image frame
The following example decodes the first frame repeatedly until its complete:
```js
let complete = false;
while (!complete) {
// The promise returned by `decode()` will only resolve when a new
// level of detail is available or the frame is complete. I.e.,
// calling `decode()` in a loop like this is won't needlessly spin.
let result = await imageDecode.decode({ completeFramesOnly: false });
// Do something with `result.image`.
complete = result.complete;
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/imagedecoder | data/mdn-content/files/en-us/web/api/imagedecoder/tracks/index.md | ---
title: "ImageDecoder: tracks property"
short-title: tracks
slug: Web/API/ImageDecoder/tracks
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ImageDecoder.tracks
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`tracks`** read-only property of the {{domxref("ImageDecoder")}} interface returns a list of the tracks in the encoded image data.
## Value
An {{domxref("ImageTrackList")}}.
## Examples
The following example prints the value of `tracks` to the console. This will be an {{domxref("ImageTrackList")}} object.
```js
console.log(imageDecoder.tracks);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/imagedecoder | data/mdn-content/files/en-us/web/api/imagedecoder/imagedecoder/index.md | ---
title: "ImageDecoder: ImageDecoder() constructor"
short-title: ImageDecoder()
slug: Web/API/ImageDecoder/ImageDecoder
page-type: web-api-constructor
status:
- experimental
browser-compat: api.ImageDecoder.ImageDecoder
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`ImageDecoder()`** constructor creates a new {{domxref("ImageDecoder")}} object which unpacks and decodes image data.
## Syntax
```js-nolint
new ImageDecoder(init)
```
### Parameters
- `init`
- : An object containing the following members:
- `type`
- : A string containing the [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) of the image file to be decoded.
- `data`
- : An {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, a {{jsxref("DataView")}}, or a {{domxref("ReadableStream")}} of bytes representing an encoded image type as described by `type`.
- `premultiplyAlpha` {{optional_inline}}
- : Specifies whether the decoded image's color channels should be premultiplied by the alpha channel. If not provided set as `"default"`:
- `"none"`
- `"premultiply"`
- `"default"`
- `colorSpaceConversion` {{optional_inline}}
- : Specifies whether the image should be decoded using color space conversion. If not provided set as `"default"`. The value `"default"` indicates that implementation-specific behavior is used:
- `"none"`
- `"default"`
- `desiredWidth` {{optional_inline}}
- : An integer indicating the desired width for the decoded output. Has no effect unless the image codec supports variable resolution decoding.
- `desiredHeight` {{optional_inline}}
- : An integer indicating the desired height for the decoded output. Has no effect unless the image codec supports variable resolution decoding.
- `preferAnimation` {{optional_inline}}
- : A {{jsxref("Boolean")}} indicating whether the initial track selection should prefer an animated track.
- `transfer`
- : An array of {{jsxref("ArrayBuffer")}}s that `ImageDecoder` will detach and take ownership of. If the array contains the {{jsxref("ArrayBuffer")}} backing `data`, `ImageDecoder` will use that buffer directly instead of copying from it.
## Examples
The following example creates a new `ImageDecoder` with the required options.
```js
let init = {
type: "image/png",
data: imageByteStream,
};
let imageDecoder = new ImageDecoder(init);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/imagedecoder | data/mdn-content/files/en-us/web/api/imagedecoder/reset/index.md | ---
title: "ImageDecoder: reset() method"
short-title: reset()
slug: Web/API/ImageDecoder/reset
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.ImageDecoder.reset
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`reset()`** method of the {{domxref("ImageDecoder")}} interface aborts all pending `decode()` operations; rejecting all pending promises. All other state will be unchanged. Class methods can continue to be invoked after `reset()`. E.g., calling `decode()` after `reset()` is permitted.
## Syntax
```js-nolint
reset()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following example resets the `ImageDecoder`.
```js
for (let i = 0; i < imageDecoder.tracks.selectedTrack.frameCount; ++i)
imageDecoder.decode({ frameIndex: i }).catch(console.log);
imageDecoder.reset();
imageDecoder.decode({ frameIndex: 0 }).then(console.log);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/imagedecoder | data/mdn-content/files/en-us/web/api/imagedecoder/type/index.md | ---
title: "ImageDecoder: type property"
short-title: type
slug: Web/API/ImageDecoder/type
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ImageDecoder.type
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`type`** read-only property of the {{domxref("ImageDecoder")}} interface reflects the [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) configured during construction.
## Value
A string containing the configured [MIME type](/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types).
## Examples
The following example prints the value of `type` to the console.
```js
console.log(imageDecoder.type);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/imagedecoder | data/mdn-content/files/en-us/web/api/imagedecoder/complete/index.md | ---
title: "ImageDecoder: complete property"
short-title: complete
slug: Web/API/ImageDecoder/complete
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.ImageDecoder.complete
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`complete`** read-only property of the {{domxref("ImageDecoder")}} interface returns true if encoded data has completed buffering.
## Value
A {{jsxref("boolean")}}, `true` if buffering is complete.
## Examples
The following example prints the value of `complete` to the console.
```js
console.log(imageDecoder.complete);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/imagedecoder | data/mdn-content/files/en-us/web/api/imagedecoder/close/index.md | ---
title: "ImageDecoder: close() method"
short-title: close()
slug: Web/API/ImageDecoder/close
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.ImageDecoder.close
---
{{securecontext_header}}{{APIRef("WebCodecs API")}}{{SeeCompatTable}}
The **`close()`** method of the {{domxref("ImageDecoder")}} interface ends all pending work and releases system resources.
## Syntax
```js-nolint
close()
```
### Parameters
None.
### Return value
None ({{jsxref("undefined")}}).
## Examples
The following example closes the `ImageDecoder`.
```js
imageDecoder.close();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/ext_texture_filter_anisotropic/index.md | ---
title: EXT_texture_filter_anisotropic extension
short-title: EXT_texture_filter_anisotropic
slug: Web/API/EXT_texture_filter_anisotropic
page-type: webgl-extension
browser-compat: api.EXT_texture_filter_anisotropic
---
{{APIRef("WebGL")}}
The **`EXT_texture_filter_anisotropic`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and exposes two constants for [anisotropic filtering (AF)](https://en.wikipedia.org/wiki/Anisotropic_filtering).
AF improves the quality of mipmapped texture access when viewing a textured primitive at an oblique angle. Using just mipmapping, these lookups have a tendency to average to grey.
WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial).
> **Note:** This extension is available to both, {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} and {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} contexts.
## Constants
- `ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT`
- : This is the `pname` argument to the {{domxref("WebGLRenderingContext.getParameter", "gl.getParameter()")}} call, and it returns the maximum available anisotropy.
- `ext.TEXTURE_MAX_ANISOTROPY_EXT`
- : This is the `pname` argument to the {{domxref("WebGLRenderingContext.getTexParameter", "gl.getTexParameter()")}} and {{domxref("WebGLRenderingContext.texParameter", "gl.texParameterf()")}} / {{domxref("WebGLRenderingContext.texParameter", "gl.texParameteri()")}} calls and sets the desired maximum anisotropy for a texture.
## Examples
```js
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
const ext =
gl.getExtension("EXT_texture_filter_anisotropic") ||
gl.getExtension("MOZ_EXT_texture_filter_anisotropic") ||
gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic");
if (ext) {
const max = gl.getParameter(ext.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
gl.texParameterf(gl.TEXTURE_2D, ext.TEXTURE_MAX_ANISOTROPY_EXT, max);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("WebGLRenderingContext.getExtension()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory/index.md | ---
title: TrustedTypePolicyFactory
slug: Web/API/TrustedTypePolicyFactory
page-type: web-api-interface
browser-compat: api.TrustedTypePolicyFactory
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`TrustedTypePolicyFactory`** interface of the {{domxref('Trusted Types API')}} creates policies and allows the verification of Trusted Type objects against created policies.
## Instance properties
- {{domxref("TrustedTypePolicyFactory.emptyHTML")}} {{ReadOnlyInline}}
- : Returns a {{domxref("TrustedHTML")}} object containing an empty string.
- {{domxref("TrustedTypePolicyFactory.emptyScript")}} {{ReadOnlyInline}}
- : Returns a {{domxref("TrustedScript")}} object containing an empty string.
- {{domxref("TrustedTypePolicyFactory.defaultPolicy")}} {{ReadOnlyInline}}
- : Returns the default {{domxref("TrustedTypePolicy")}} or null if this is empty.
## Instance methods
- {{domxref("TrustedTypePolicyFactory.createPolicy()")}}
- : Creates a {{domxref("TrustedTypePolicy")}} object that implements the rules passed as `policyOptions`.
- {{domxref("TrustedTypePolicyFactory.isHTML()")}}
- : When passed a value checks that it is a valid {{domxref("TrustedHTML")}} object.
- {{domxref("TrustedTypePolicyFactory.isScript()")}}
- : When passed a value checks that it is a valid {{domxref("TrustedScript")}} object.
- {{domxref("TrustedTypePolicyFactory.isScriptURL()")}}
- : When passed a value checks that it is a valid {{domxref("TrustedScriptURL")}} object.
- {{domxref("TrustedTypePolicyFactory.getAttributeType()")}}
- : Allows web developers to check whether a Trusted Type is required for an element and attribute, and if so which one.
- {{domxref("TrustedTypePolicyFactory.getPropertyType()")}}
- : Allows web developers to check whether a Trusted Type is required for a property, and if so which one.
## Examples
The below code creates a policy with the name `"myEscapePolicy"` with a function defined for `createHTML()` which sanitizes HTML.
We then use the policy to sanitize a string, creating a {{domxref("TrustedHTML")}} object, `escaped`. This object can be tested with {{domxref("TrustedTypePolicyFactory.isHTML","isHTML()")}} to ensure that it was created by one of our policies.
```js
const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {
createHTML: (string) => string.replace(/>/g, "<"),
});
const escaped = escapeHTMLPolicy.createHTML("<img src=x onerror=alert(1)>");
console.log(trustedTypes.isHTML(escaped)); // true;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory | data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory/emptyhtml/index.md | ---
title: "TrustedTypePolicyFactory: emptyHTML property"
short-title: emptyHTML
slug: Web/API/TrustedTypePolicyFactory/emptyHTML
page-type: web-api-instance-property
browser-compat: api.TrustedTypePolicyFactory.emptyHTML
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`emptyHTML`** read-only property of the {{domxref("TrustedTypePolicyFactory")}} interface returns a {{domxref("TrustedHTML")}} object containing an empty string.
This object can be used when the application requires an empty string to be inserted into an injection sink.
## Value
A {{domxref("TrustedHTML")}} object.
## Examples
In the below example an empty string is to be inserted into the element. Therefore there is no need to create a policy, and the `emptyHTML` property can be used to insert the empty element when a Trusted Types object is expected.
```js
el.innerHTML = trustedTypes.emptyHTML;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory | data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory/getpropertytype/index.md | ---
title: "TrustedTypePolicyFactory: getPropertyType() method"
short-title: getPropertyType()
slug: Web/API/TrustedTypePolicyFactory/getPropertyType
page-type: web-api-instance-method
browser-compat: api.TrustedTypePolicyFactory.getPropertyType
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`getPropertyType()`** method of the {{domxref("TrustedTypePolicyFactory")}} interface allows web developers to check if a Trusted Type is required for an element's property.
## Syntax
```js-nolint
getPropertyType(tagName, property)
getPropertyType(tagName, property, elementNS)
```
### Parameters
- `tagName`
- : A string containing the name of an HTML tag.
- `property`
- : A string containing a property, for example `"innerHTML"`.
- `elementNS` {{optional_inline}}
- : A string containing a namespace, if empty defaults to the HTML namespace.
### Return value
A string with one of:
- `"TrustedHTML"`
- `"TrustedScript"`
- `"TrustedScriptURL"`
Or, null.
## Examples
In this example, passing the {{htmlelement("div")}} element and `innerHTML` property to `getPropertyType` returns "TrustedHTML".
```js
console.log(trustedTypes.getPropertyType("div", "innerHTML")); // "TrustedHTML"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory | data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory/defaultpolicy/index.md | ---
title: "TrustedTypePolicyFactory: defaultPolicy property"
short-title: defaultPolicy
slug: Web/API/TrustedTypePolicyFactory/defaultPolicy
page-type: web-api-instance-property
browser-compat: api.TrustedTypePolicyFactory.defaultPolicy
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`defaultPolicy`** read-only property of the {{domxref("TrustedTypePolicyFactory")}} interface returns the default {{domxref("TrustedTypePolicy")}} or null if this is empty.
> **Note:** Information about the creation and use of default policies can be found in the [`createPolicy()`](/en-US/docs/Web/API/TrustedTypePolicyFactory/createPolicy#default_policy) documentation.
## Value
A {{domxref("TrustedTypePolicy")}} or null.
## Examples
The first line below returns null as no default policy has been created. Once a default policy is created, calling `defaultPolicy` returns that policy object.
```js
console.log(trustedTypes.defaultPolicy); // null
const dp = trustedTypes.createPolicy("default", {});
console.log(trustedTypes.defaultPolicy); // a TrustedTypePolicy object
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory | data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory/isscript/index.md | ---
title: "TrustedTypePolicyFactory: isScript() method"
short-title: isScript()
slug: Web/API/TrustedTypePolicyFactory/isScript
page-type: web-api-instance-method
browser-compat: api.TrustedTypePolicyFactory.isScript
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`isScript()`** method of the {{domxref("TrustedTypePolicyFactory")}} interface returns true if it is passed a valid {{domxref("TrustedScript")}} object.
> **Note:** The purpose of the functions `isScript()`, {{domxref("TrustedTypePolicyFactory.isHTML","isHTML()")}}, and {{domxref("TrustedTypePolicyFactory.isScriptURL","isScriptURL()")}} is to check if the object is a valid TrustedType object, created by a configured policy.
## Syntax
```js-nolint
isScript(value)
```
### Parameters
- `value`
- : A {{domxref("TrustedScript")}} object.
### Return value
A {{jsxref("boolean")}} that is true if the object is a valid {{domxref("TrustedScript")}} object.
## Examples
In the below example the constant `url` was created by a policy, and therefore `isScriptURL()` returns true. The second example is an attempt to fake an object, and the third is a string. Both of these will return false when passed to `isScriptURL()`.
```js
const myScript = policy.createScript("eval('2 + 2')");
console.log(trustedTypes.isScript(myScript)); // true;
const fake = Object.create(TrustedScript.prototype);
console.log(trustedTypes.isScript(fake)); // false
console.log(trustedTypes.isScript("eval('2 + 2')")); // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory | data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory/emptyscript/index.md | ---
title: "TrustedTypePolicyFactory: emptyScript property"
short-title: emptyScript
slug: Web/API/TrustedTypePolicyFactory/emptyScript
page-type: web-api-instance-property
browser-compat: api.TrustedTypePolicyFactory.emptyScript
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`emptyScript`** read-only property of the {{domxref("TrustedTypePolicyFactory")}} interface returns a {{domxref("TrustedScript")}} object containing an empty string.
This object can be used when the application requires an empty string to be inserted into an injection sink which is expecting a `TrustedScript` object.
## Value
A {{domxref("TrustedScript")}} object.
## Examples
The [specification](https://w3c.github.io/trusted-types/dist/spec/#dom-trustedtypepolicyfactory-emptyscript) explains that the `emptyScript` object can be used to detect support for dynamic code compilation.
Native Trusted Types implementations can support `eval(TrustedScript)`, therefore in the below example a native implementation will return false for `eval(trustedTypes.emptyScript)`. A polyfill will return a truthy object.
```js
const supportsTS = !eval(trustedTypes.emptyScript);
eval(supportsTS ? myTrustedScriptObj : myTrustedScriptObj.toString());
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory | data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory/getattributetype/index.md | ---
title: "TrustedTypePolicyFactory: getAttributeType() method"
short-title: getAttributeType()
slug: Web/API/TrustedTypePolicyFactory/getAttributeType
page-type: web-api-instance-method
browser-compat: api.TrustedTypePolicyFactory.getAttributeType
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`getAttributeType()`** method of the {{domxref("TrustedTypePolicyFactory")}} interface allows web developers to check if a Trusted Type is required for an element, and if so which Trusted Type is used.
## Syntax
```js-nolint
getAttributeType(tagName, attribute)
getAttributeType(tagName, attribute, elementNS)
getAttributeType(tagName, attribute, elementNS, attrNS)
```
### Parameters
- `tagName`
- : A string containing the name of an HTML tag.
- `attribute`
- : A string containing an attribute.
- `elementNS` {{optional_inline}}
- : A string containing a namespace, if empty defaults to the HTML namespace.
- `attrNS` {{optional_inline}}
- : A string containing a namespace, if empty defaults to null.
### Return value
A string with one of:
- `"TrustedHTML"`
- `"TrustedScript"`
- `"TrustedScriptURL"`
Or, null.
## Examples
In this example, passing the {{htmlelement("script")}} element and [`src`](/en-US/docs/Web/HTML/Global_attributes#src) attribute to `getAttributeType` returns "TrustedScriptURL".
```js
console.log(trustedTypes.getAttributeType("script", "src")); // "TrustedScriptURL"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory | data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory/isscripturl/index.md | ---
title: "TrustedTypePolicyFactory: isScriptURL() method"
short-title: isScriptURL()
slug: Web/API/TrustedTypePolicyFactory/isScriptURL
page-type: web-api-instance-method
browser-compat: api.TrustedTypePolicyFactory.isScriptURL
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`isScriptURL()`** method of the {{domxref("TrustedTypePolicyFactory")}} interface returns true if it is passed a valid {{domxref("TrustedScriptURL")}} object.
> **Note:** The purpose of the functions `isScriptURL()`, {{domxref("TrustedTypePolicyFactory.isHTML","isHTML()")}}, and {{domxref("TrustedTypePolicyFactory.isScript","isScript()")}} is to check if the object is a valid TrustedType object, created by a configured policy.
## Syntax
```js-nolint
isScriptURL(value)
```
### Parameters
- `value`
- : A {{domxref("TrustedScriptURL")}} object.
### Return value
A {{jsxref("boolean")}}that is true if the object is a valid {{domxref("TrustedScriptURL")}} object.
## Examples
In the below example the constant `url` was created by a policy, and therefore `isScriptURL()` returns true. The second example is an attempt to fake an object, and the third is a string. Both of these will return false when passed to `isScriptURL()`.
```js
const url = policy.createScriptURL("https://example.com/myscript.js");
console.log(trustedTypes.isScriptURL(url)); // true;
const fake = Object.create(TrustedScriptURL.prototype);
console.log(trustedTypes.isScriptURL(fake)); // false
console.log(trustedTypes.isScriptURL("https://example.com/myscript.js")); // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory | data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory/ishtml/index.md | ---
title: "TrustedTypePolicyFactory: isHTML() method"
short-title: isHTML()
slug: Web/API/TrustedTypePolicyFactory/isHTML
page-type: web-api-instance-method
browser-compat: api.TrustedTypePolicyFactory.isHTML
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`isHTML()`** method of the {{domxref("TrustedTypePolicyFactory")}} interface returns true if it is passed a valid {{domxref("TrustedHTML")}} object.
> **Note:** The purpose of the functions `isHTML()`, {{domxref("TrustedTypePolicyFactory.isScript","isScript()")}}, and {{domxref("TrustedTypePolicyFactory.isScriptURL","isScriptURL()")}} is to check if the object is a valid TrustedType object, created by a configured policy.
## Syntax
```js-nolint
isHTML(value)
```
### Parameters
- `value`
- : A {{domxref("TrustedHTML")}} object.
### Return value
A {{jsxref("boolean")}} that is true if the object is a valid {{domxref("TrustedHTML")}} object.
## Examples
In the below example the constant `html` was created by a policy, and therefore `isHTML()` returns true. The second example is an attempt to fake an object, and the third is a string. Both of these will return false when passed to `isHTML()`.
```js
const html = policy.createHTML("<div>");
console.log(trustedTypes.isHTML(html)); // true;
const fake = Object.create(TrustedHTML.prototype);
console.log(trustedTypes.isHTML(fake)); // false
console.log(trustedTypes.isHTML("<div>plain string</div>")); // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory | data/mdn-content/files/en-us/web/api/trustedtypepolicyfactory/createpolicy/index.md | ---
title: "TrustedTypePolicyFactory: createPolicy() method"
short-title: createPolicy()
slug: Web/API/TrustedTypePolicyFactory/createPolicy
page-type: web-api-instance-method
browser-compat: api.TrustedTypePolicyFactory.createPolicy
---
{{DefaultAPISidebar("Trusted Types API")}}
The **`createPolicy()`** method of the {{domxref("TrustedTypePolicyFactory")}} interface creates a {{domxref("TrustedTypePolicy")}} object that implements the rules passed as `policyOptions`.
### The default policy
In Chrome a policy with a name of "default" creates a special policy that will be used if a string (rather than a Trusted Type object) is passed to an injection sink. This can be used in a transitional phase while moving from an application that inserted strings into injection sinks.
> **Note:** The above behavior is not yet settled in the specification and may change in future.
> **Warning:** A lax default policy could defeat the purpose of using Trusted Types, and therefore should be defined with strict rules to ensure it cannot be used to run dangerous code.
## Syntax
```js-nolint
createPolicy(policyName, policyOptions)
```
### Parameters
- `policyName`
- : A string with the name of the policy.
- `policyOptions` {{optional_inline}}
- : User-defined functions for converting strings into trusted values.
- `createHTML(input[,args])`
- : A callback function in the form of a string that contains code to run when creating a {{domxref("TrustedHTML")}} object.
- `createScript(input[,args])`
- : A callback function in the form of a string that contains code to run when creating a {{domxref("TrustedScript")}} object.
- `createScriptURL(input[,args])`
- : A callback function in the form of a string that contains code to run when creating a {{domxref("TrustedScriptURL")}} object.
### Return value
A {{domxref("TrustedTypePolicy")}} object.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if policy names are restricted by the [Content Security Policy `trusted-types` directive](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/trusted-types) and this name is not on the allowlist.
- {{jsxref("TypeError")}}
- : Thrown if the name is a duplicate and the [Content Security Policy trusted-types directive](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/trusted-types) is not using `allow-duplicates`.
## Examples
The below code creates a policy with the name `"myEscapePolicy"` with a function defined for `createHTML()` which sanitizes HTML.
```js
const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {
createHTML: (string) => string.replace(/>/g, "<"),
});
```
### Creating a default policy
On a site where Trusted Types are enforced via a Content Security Policy with the [`require-trusted-types-for`](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/require-trusted-types-for) directive set to `script`, any injection script that accepts a script expects a Trusted Type object. In the case that a string is inserted instead, the following default policy will be used.
The policy logs a message to the console to remind the developer to refactor this part of the application to use a Trusted Type object. It also appends details of the use of the default policy, type, and injection sink to the returned value.
```js
trustedTypes.createPolicy("default", {
createScriptURL: (s, type, sink) => {
console.log("Please refactor.");
return `${s}?default-policy-used&type=${encodeURIComponent(
type,
)}&sink=${encodeURIComponent(sink)}`;
},
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webvr_api/index.md | ---
title: WebVR API
slug: Web/API/WebVR_API
page-type: web-api-overview
status:
- deprecated
- non-standard
browser-compat: api.Navigator.getVRDisplays
---
{{DefaultAPISidebar("WebVR API")}}{{Deprecated_Header}}{{Non-standard_header}}
> **Note:** WebVR API is replaced by [WebXR API](/en-US/docs/Web/API/WebXR_Device_API). WebVR was never ratified as a standard, was implemented and enabled by default in very few browsers and supported a small number of devices.
WebVR provides support for exposing virtual reality devices — for example, head-mounted displays like the Oculus Rift or HTC Vive — to web apps, enabling developers to translate position and movement information from the display into movement around a 3D scene. This has numerous, interesting applications, from virtual product tours and interactive training apps to immersive first-person games.
## Concepts and usage
Any VR devices attached to your computer will be returned by the {{DOMxRef("Navigator.getVRDisplays()")}} method; each one will be represented by a {{DOMxRef("VRDisplay")}} object.

{{DOMxRef("VRDisplay")}} is the central interface in the WebVR API — via its properties and methods you can access functionality to:
- Retrieve useful information to allow us to identify the display, what capabilities it has, controllers associated with it, and more.
- Retrieve {{DOMxRef("VRFrameData", "frame data")}} for each frame of content you want to present in a display, and submit those frames for display at a consistent rate.
- Start and stop presenting to the display.
A typical (simple) WebVR app would work like so:
1. {{DOMxRef("Navigator.getVRDisplays()")}} is used to get a reference to your VR display.
2. {{DOMxRef("VRDisplay.requestPresent()")}} is used to start presenting to the VR display.
3. WebVR's dedicated {{DOMxRef("VRDisplay.requestAnimationFrame()")}} method is used to run the app's rendering loop at the correct refresh rate for the display.
4. Inside the rendering loop, you grab the data required to display the current frame ({{DOMxRef("VRDisplay.getFrameData()")}}), draw the displayed scene twice — once for the view in each eye, then submit the rendered view to the display to show to the user ({{DOMxRef("VRDisplay.submitFrame()")}}).
In addition, WebVR 1.1 adds a number of events on the {{DOMxRef("Window")}} object to allow JavaScript to respond to changes to the status of the display.
> **Note:** You can find a lot more out about how the API works in our [Using the WebVR API](/en-US/docs/Web/API/WebVR_API/Using_the_WebVR_API) and [WebVR Concepts](/en-US/docs/Web/API/WebVR_API/Concepts) articles.
### API availability
The WebVR API, which was never ratified as a web standard, has been deprecated in favor of the [WebXR API](/en-US/docs/Web/API/WebXR_Device_API), which is well on track toward finishing the standardization process. As such, you should try to update existing code to use the newer API instead. Generally the transition should be fairly painless.
Additionally, on some devices and/or browsers, WebVR requires that the page be loaded using a secure context, over an HTTPS connection. If the page is not fully secure, the WebVR methods and functions will not be available. You can easily test for this by checking to see if the {{domxref("Navigator")}} method {{domxref("Navigator.getVRDisplays", "getVRDisplays()")}} is `NULL`:
```js
if (!navigator.getVRDisplays) {
console.error("WebVR is not available");
} else {
/* Use WebVR */
}
```
### Using controllers: Combining WebVR with the Gamepad API
Many WebVR hardware setups feature controllers that go along with the headset. These can be used in WebVR apps via the [Gamepad API](/en-US/docs/Web/API/Gamepad_API), and specifically the [Gamepad Extensions API](/en-US/docs/Web/API/Gamepad_API#experimental_gamepad_extensions) that adds API features for accessing [controller pose](/en-US/docs/Web/API/GamepadPose), [haptic actuators](/en-US/docs/Web/API/GamepadHapticActuator), and more.
> **Note:** Our [Using VR controllers with WebVR](/en-US/docs/Web/API/WebVR_API/Using_VR_controllers_with_WebVR) article explains the basics of how to use VR controllers with WebVR apps.
## WebVR interfaces
- {{DOMxRef("VRDisplay")}}
- : Represents any VR device supported by this API. It includes generic information such as device IDs and descriptions, as well as methods for starting to present a VR scene, retrieving eye parameters and display capabilities, and other important functionality.
- {{DOMxRef("VRDisplayCapabilities")}}
- : Describes the capabilities of a {{DOMxRef("VRDisplay")}} — its features can be used to perform VR device capability tests, for example can it return position information.
- {{DOMxRef("VRDisplayEvent")}}
- : Represents the event object of WebVR-related events (see the [window object extensions](#window) listed below).
- {{DOMxRef("VRFrameData")}}
- : Represents all the information needed to render a single frame of a VR scene; constructed by {{DOMxRef("VRDisplay.getFrameData()")}}.
- {{DOMxRef("VRPose")}}
- : Represents the position state at a given timestamp (which includes orientation, position, velocity, and acceleration).
- {{DOMxRef("VREyeParameters")}}
- : Provides access to all the information required to correctly render a scene for each given eye, including field of view information.
- {{DOMxRef("VRFieldOfView")}}
- : Represents a field of view defined by 4 different degree values describing the view from a center point.
- {{DOMxRef("VRLayerInit")}}
- : Represents a layer to be presented in a {{DOMxRef("VRDisplay")}}.
- {{DOMxRef("VRStageParameters")}}
- : Represents the values describing the stage area for devices that support room-scale experiences.
### Extensions to other interfaces
The WebVR API extends the following APIs, adding the listed features.
#### Gamepad
- {{DOMxRef("Gamepad.displayId")}} {{ReadOnlyInline}}
- : _Returns the {{DOMxRef("VRDisplay.displayId")}} of the associated {{DOMxRef("VRDisplay")}} — the `VRDisplay` that the gamepad is controlling the displayed scene of._
#### Navigator
- {{DOMxRef("Navigator.activeVRDisplays")}} {{ReadOnlyInline}}
- : Returns an array containing every {{DOMxRef("VRDisplay")}} object that is currently presenting ({{DOMxRef("VRDisplay.ispresenting")}} is `true`).
- {{DOMxRef("Navigator.getVRDisplays()")}}
- : Returns a promise that resolves to an array of {{DOMxRef("VRDisplay")}} objects representing any available VR displays connected to the computer.
#### Window events
- {{DOMxRef("Window.vrdisplaypresentchange_event", "vrdisplaypresentchange")}}
- : Fired when the presenting state of a VR display changes — i.e. goes from presenting to not presenting or vice versa.
- {{DOMxRef("Window.vrdisplayconnect_event", "vrdisplayconnect")}}
- : Fired when a compatible VR display has been connected to the computer.
- {{DOMxRef("Window.vrdisplaydisconnect_event", "vrdisplaydisconnect")}}
- : Fired when a compatible VR display has been disconnected from the computer.
- {{DOMxRef("Window.vrdisplayactivate_event", "vrdisplayactivate")}}
- : Fired when a display is able to be presented to.
- {{DOMxRef("Window.vrdisplaydeactivate_event", "vrdisplaydeactivate")}}
- : Fired when a display can no longer be presented to.
## Examples
You can find a number of examples at these locations:
- [webvr-tests](https://github.com/mdn/webvr-tests) — very simple examples to accompany the MDN WebVR documentation.
- [Carmel starter kit](https://github.com/facebookarchive/Carmel-Starter-Kit) — nice simple, well-commented examples that go along with Carmel, Facebook's WebVR browser.
- [WebVR.info samples](https://webvr.info/samples/) — slightly more in-depth examples plus source code
- [WebVR.rocks Firefox demos](https://webvr.rocks/firefox#demos) — showcase examples
- [A-Frame homepage](https://aframe.io/) — examples showing A-Frame usage
## Specifications
This API was specified in the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard.
Until all browsers have implemented the new [WebXR APIs](/en-US/docs/Web/API/WebXR_Device_API/Fundamentals), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/).
## Browser compatibility
{{Compat}}
## See also
- [A-Frame](https://aframe.io/) — Open source web framework for building VR experiences.
- [webvr.info](https://webvr.info) — Up-to-date information about WebVR, browser setup, and community.
- [threejs-vr-boilerplate](https://github.com/MozillaReality/vr-web-examples/tree/master/threejs-vr-boilerplate) — A useful starter template for writing WebVR apps into.
- [Web VR polyfill](https://github.com/immersive-web/webvr-polyfill) — JavaScript implementation of WebVR.
- [Supermedium](https://www.supermedium.com) — A pure WebVR browser to easily access the best WebVR content.
- [WebVR Directory](https://webvr.directory/) — List of quality WebVR sites.
| 0 |
data/mdn-content/files/en-us/web/api/webvr_api | data/mdn-content/files/en-us/web/api/webvr_api/using_vr_controllers_with_webvr/index.md | ---
title: Using VR controllers with WebVR
slug: Web/API/WebVR_API/Using_VR_controllers_with_WebVR
page-type: guide
status:
- experimental
---
{{APIRef("WebVR API")}}{{Deprecated_Header}}
Many WebVR hardware setups feature controllers that go along with the headset. These can be used in WebVR apps via the [Gamepad API](/en-US/docs/Web/API/Gamepad_API), and specifically the [Gamepad Extensions API](/en-US/docs/Web/API/Gamepad_API#experimental_gamepad_extensions) that adds API features for accessing [controller pose](/en-US/docs/Web/API/GamepadPose), [haptic actuators](/en-US/docs/Web/API/GamepadHapticActuator), and more. This article explains the basics.
> **Note:** WebVR API is replaced by [WebXR API](/en-US/docs/Web/API/WebXR_Device_API). WebVR was never ratified as a standard, was implemented and enabled by default in very few browsers and supported a small number of devices.
## The WebVR API
The [WebVR API](/en-US/docs/Web/API/WebVR_API) is a nascent, but very interesting new feature of the web platform that allows developers to create web-based virtual reality experiences. It does this by providing access to VR headsets connected to your computer as {{domxref("VRDisplay")}} objects, which can be manipulated to start and stop presentation to the display, queried for movement data (e.g. orientation and position) that can be used to update the display on each frame of the animation loop, and more.
Before you read this article, you should really be familiar with the basics of the WebVR API already — go and read [Using the WebVR API](/en-US/docs/Web/API/WebVR_API/Using_the_WebVR_API) first, if you haven't already done so, which also details browser support and required hardware setup.
## The Gamepad API
The [Gamepad API](/en-US/docs/Web/API/Gamepad_API) is a fairly well-supported API that allows developers to access gamepads/controllers connected to your computer and use them to control web apps. The basic Gamepad API provides access to connected controllers as {{domxref("Gamepad")}} objects, which can then be queried to find out what buttons are being pressed and thumbsticks (axes) are being moved at any point, etc.
You can find more about basic Gamepad API usage in [Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API), and [Implementing controls using the Gamepad API](/en-US/docs/Games/Techniques/Controls_Gamepad_API).
However, in this article we will mainly be concentrating on some of the new features provided by the [Gamepad Extensions](https://w3c.github.io/gamepad/extensions.html) API, which allows access to advanced controller information such as position and orientation data, control over haptic actuators (e.g. vibration hardware), and more. This API is very new, and currently is only supported and enabled by default in Firefox 55+ Beta/Nightly channels.
## Types of controller
There are two types of controller you'll encounter with VR hardware:
- 6DoF (six-degrees-of-freedom) controllers provide access to both positional and orientation data — they can manipulate a VR scene and the objects it contains with movement but also rotation. A good example is the HTC VIVE controllers.
- 3DoF (three-degrees-of-freedom) controllers provide orientation but not positional data. A good example is the Google Daydream controller, which can be rotated to point to different things in 3D space like a laser pointer, but can't be moved inside a 3D scene.
## Basic controller access
Now onto some code. Let's look first at the basics of how we get access to VR controllers with the Gamepad API. There are a few strange nuances to bear in mind here, so it is worth taking a look.
We've written up a simple example to demonstrate — see our [vr-controller-basic-info](https://github.com/mdn/webvr-tests/blob/main/webvr/vr-controller-basic-info/index.html) source code ([see it running live here also](https://mdn.github.io/webvr-tests/webvr/vr-controller-basic-info/)). This demo outputs information on the VR displays and gamepads connected to your computer.
### Getting the display information
The first notable code is as follows:
```js
let initialRun = true;
if (navigator.getVRDisplays && navigator.getGamepads) {
info.textContent = "WebVR API and Gamepad API supported.";
reportDisplays();
} else {
info.textContent =
"WebVR API and/or Gamepad API not supported by this browser.";
}
```
Here we first use a tracking variable, `initialRun`, to note that this is the first time we have loaded the page. You'll find out more about this later on. Next, we detect to see if the WebVR and Gamepad APIs are supported by checking for the existence of the {{domxref("Navigator.getVRDisplays()")}} and {{domxref("Navigator.getGamepads()")}} methods. If so, we run our `reportDisplays()` custom function to start the process off. This function looks like so:
```js
function reportDisplays() {
navigator.getVRDisplays().then((displays) => {
console.log(`${displays.length} displays`);
displays.forEach((display, i) => {
const cap = display.capabilities;
// cap is a VRDisplayCapabilities object
const listItem = document.createElement("li");
listItem.innerHTML =
`<strong>Display ${i + 1}</strong><br>` +
`VR Display ID: ${display.displayId}<br>` +
`VR Display Name: ${display.displayName}<br>` +
`Display can present content: ${cap.canPresent}<br>` +
`Display is separate from the computer's main display: ${cap.hasExternalDisplay}<br>` +
`Display can return position info: ${cap.hasPosition}<br>` +
`Display can return orientation info: ${cap.hasOrientation}<br>` +
`Display max layers: ${cap.maxLayers}`;
list.appendChild(listItem);
});
setTimeout(reportGamepads, 1000);
// For VR, controllers will only be active after their corresponding headset is active
});
}
```
This function first uses the promise-based {{domxref("Navigator.getVRDisplays()")}} method, which resolves with an array containing {{domxref("VRDisplay")}} objects representing the connected displays. Next, it prints out each display's {{domxref("VRDisplay.displayId")}} and {{domxref("VRDisplay.displayName")}} values, and a number of useful values contained in the display's associated {{domxref("VRCapabilities")}} object. The most useful of these are {{domxref("VRCapabilities.hasOrientation","hasOrientation")}} and {{domxref("VRCapabilities.hasPosition","hasPosition")}}, which allow you to detect whether the device can return orientation and position data and set up your app accordingly.
The last line contained in this function is a {{domxref("setTimeout()")}} call, which runs the `reportGamepads()` function after a 1 second delay. Why do we need to do this? First of all, VR controllers will only be ready after their associated VR headset is active, so we need to invoke this after `getVRDisplays()` has been called and returned the display information. Second, the Gamepad API is much older than the WebVR API, and not promise-based. As you'll see later, the `getGamepads()` method is synchronous, and just returns the `Gamepad` objects immediately — it doesn't wait for the controller to be ready to report information. Unless you wait for a little while, returned information may not be accurate (at least, this is what we found in our tests).
### Getting the Gamepad information
The `reportGamepads()` function looks like this:
```js
function reportGamepads() {
const gamepads = navigator.getGamepads();
console.log(`${gamepads.length} controllers`);
for (const gp of gamepads) {
const listItem = document.createElement("li");
listItem.classList = "gamepad";
listItem.innerHTML =
`<strong>Gamepad ${gp.index}</strong> (${gp.id})<br>` +
`Associated with VR Display ID: ${gp.displayId}<br>` +
`Gamepad associated with which hand: ${gp.hand}<br>` +
`Available haptic actuators: ${gp.hapticActuators.length}<br>` +
`Gamepad can return position info: ${gp.pose.hasPosition}<br>` +
`Gamepad can return orientation info: ${gp.pose.hasOrientation}`;
list.appendChild(listItem);
}
initialRun = false;
}
```
This works in a similar manner to `reportDisplays()` — we get an array of {{domxref("Gamepad")}} objects using the non-promise-based `getGamepads()` method, then cycle through each one and print out information on each:
- The {{domxref("Gamepad.displayId")}} property is the same as the `displayId` of the headset the controller is associated with, and therefore useful for tying controller and headset information together.
- The {{domxref("Gamepad.index")}} property is unique numerical index that identifies each connected controller.
- {{domxref("Gamepad.hand")}} returns which hand the controller is expected to be held in.
- {{domxref("Gamepad.hapticActuators")}} returns an array of the haptic actuators available in the controller. Here we are returning its length so we can see how many each has available.
- Finally, we return {{domxref("GamepadPose.hasPosition")}} and {{domxref("GamepadPose.hasOrientation")}} to show whether the controller can return position and orientation data. This works just the same as for the displays, except that in the case of gamepads these values are available on the pose object, not the capabilities object.
Note that we also gave each list item containing controller information a class name of `gamepad`. We'll explain what this is for later.
The last thing to do here is set the `initialRun` variable to `false`, as the initial run is now over.
### Gamepad events
To finish off this section, we'll look at the gamepad-associated events. There are two we need concern ourselves with — {{domxref("Window.gamepadconnected_event", "gamepadconnected")}} and {{domxref("Window.gamepaddisconnected_event", "gamepaddisconnected")}} — and it is fairly obvious what they do.
At the end of our example we first include the `removeGamepads()` function:
```js
function removeGamepads() {
const gpLi = document.querySelectorAll(".gamepad");
for (let i = 0; i < gpLi.length; i++) {
list.removeChild(gpLi[i]);
}
reportGamepads();
}
```
This function grabs references to all list items with a class name of `gamepad`, and removes them from the DOM. Then it re-runs `reportGamepads()` to populate the list with the updated list of connected controllers.
`removeGamepads()` will be run each time a gamepad is connected or disconnected, via the following event handlers:
```js
window.addEventListener("gamepadconnected", (e) => {
info.textContent = `Gamepad ${e.gamepad.index} connected.`;
if (!initialRun) {
setTimeout(removeGamepads, 1000);
}
});
window.addEventListener("gamepaddisconnected", (e) => {
info.textContent = `Gamepad ${e.gamepad.index} disconnected.`;
setTimeout(removeGamepads, 1000);
});
```
We have `setTimeout()` calls in place here — like we did with the initialization code at the top of the script — to make sure that the gamepads are ready to report their information when `reportGamepads()` is called in each case.
But there's one more thing to note — you'll see that inside the `gamepadconnected` handler, the timeout is only run if `initialRun` is `false`. This is because if your gamepads are connected when the document first loads, `gamepadconnected` is fired once for each gamepad, therefore `removeGamepads()`/`reportGamepads()` will be run several times. This could lead to inaccurate results, therefore we only want to run `removeGamepads()` inside the `gamepadconnected` handler after the initial run, not during it. This is what `initialRun` is for.
## Introducing a real demo
Now let's look at the Gamepad API being used inside a real WebVR demo. You can find this demo at [raw-webgl-controller-example](https://github.com/mdn/webvr-tests/tree/main/webvr/raw-webgl-controller-example) ([see it live here also](https://mdn.github.io/webvr-tests/webvr/raw-webgl-controller-example/)).
In exactly the same way as our [raw-webgl-example](https://github.com/mdn/webvr-tests/tree/main/webvr/raw-webgl-example) (see [Using the WebVR API](/en-US/docs/Web/API/WebVR_API/Using_the_WebVR_API) for details), this renders a spinning 3D cube, which you can choose to present in a VR display. The only difference is that, while in VR presenting mode, this demo allows you to move the cube by moving a VR controller (the original demo moves the cube as you move your VR headset).
We'll explore the code differences in this version below — see [webgl-demo.js](https://github.com/mdn/webvr-tests/blob/main/webvr/raw-webgl-controller-example/webgl-demo.js).
### Accessing the gamepad data
Inside the `drawVRScene()` function, you'll find this bit of code:
```js
const gamepads = navigator.getGamepads();
const gp = gamepads[0];
if (gp) {
const gpPose = gp.pose;
const curPos = gpPose.position;
const curOrient = gpPose.orientation;
if (poseStatsDisplayed) {
displayPoseStats(gpPose);
}
}
```
Here we get the connected gamepads with {{domxref("Navigator.getGamepads")}}, then store the first gamepad detected in the `gp` variable. As we only need one gamepad for this demo, we'll just ignore the others.
The next thing we do is to get the {{domxref("GamepadPose")}} object for the controller stored in gpPose (by querying {{domxref("Gamepad.pose")}}), and also store the current gamepad position and orientation for this frame in variables so they are easy to access later. We also display the post stats for this frame in the DOM using the `displayPoseStats()` function. All of this is only done if `gp` actually has a value (if a gamepad is connected), which stops the demo erroring if we don't have our gamepad connected.
Slightly later in the code, you can find this block:
```js
if (gp && gpPose.hasPosition) {
mvTranslate([
0.0 + curPos[0] * 15 - curOrient[1] * 15,
0.0 + curPos[1] * 15 + curOrient[0] * 15,
-15.0 + curPos[2] * 25,
]);
} else if (gp) {
mvTranslate([0.0 + curOrient[1] * 15, 0.0 + curOrient[0] * 15, -15.0]);
} else {
mvTranslate([0.0, 0.0, -15.0]);
}
```
Here we alter the position of the cube on the screen according to the {{domxref("GamepadPose.position","position")}} and {{domxref("GamepadPose.orientation","orientation")}} data received from the connected controller. These values (stored in `curPos` and `curOrient`) are {{jsxref("Float32Array")}}s containing the X, Y, and Z values (here we are just using \[0] which is X, and \[1] which is Y).
If the `gp` variable has a `Gamepad` object inside it and it can return position values (`gpPose.hasPosition`), indicating a 6DoF controller, we modify the cube position using position and orientation values. If only the former is true, indicating a 3DoF controller, we modify the cube position using the orientation values only. If there is no gamepad connected, we don't modify the cube position at all.
### Displaying the gamepad pose data
In the `displayPoseStats()` function, we grab all of the data we want to display out of the {{domxref("GamepadPose")}} object passed into it, then print them into the UI panel that exists in the demo for displaying such data:
```js
function displayPoseStats(pose) {
const pos = pose.position;
const formatCoords = ([x, y, z]) =>
`x ${x.toFixed(3)}, y ${y.toFixed(3)}, z ${z.toFixed(3)}`;
posStats.textContent = pose.hasPosition
? `Position: ${formatCoords(pose.position)}`
: "Position not reported";
orientStats.textContent = pose.hasOrientation
? `Orientation: ${formatCoords(pose.orientation)}`
: "Orientation not reported";
linVelStats.textContent = `Linear velocity: ${formatCoords(
pose.linearVelocity,
)}`;
angVelStats.textContent = `Angular velocity: ${formatCoords(
pose.angularVelocity,
)}`;
linAccStats.textContent = pose.linearAcceleration
? `Linear acceleration: ${formatCoords(pose.linearAcceleration)}`
: "Linear acceleration not reported";
angAccStats.textContent = pose.angularAcceleration
? `Angular acceleration: ${formatCoords(pose.angularAcceleration)}`
: "Angular acceleration not reported";
}
```
## Summary
This article has given you a very basic idea of how to use the Gamepad Extensions to use VR controllers inside WebVR apps. In a real app you'd probably have a much more complex control system in effect, with controls assigned to the buttons on the VR controllers, and the display being affected by both the display pose and the controller poses simultaneously. Here however, we just wanted to isolate the pure Gamepad Extensions parts of that.
## See also
- [WebVR API](/en-US/docs/Web/API/WebVR_API)
- [Gamepad API](/en-US/docs/Web/API/Gamepad_API)
- [Using the WebVR API](/en-US/docs/Web/API/WebVR_API/Using_the_WebVR_API)
- [Implementing controls using the Gamepad API](/en-US/docs/Games/Techniques/Controls_Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/webvr_api | data/mdn-content/files/en-us/web/api/webvr_api/using_the_webvr_api/index.md | ---
title: Using the WebVR API
slug: Web/API/WebVR_API/Using_the_WebVR_API
page-type: guide
---
{{APIRef("WebVR API")}}{{deprecated_header}}
> **Note:** WebVR API is replaced by [WebXR API](/en-US/docs/Web/API/WebXR_Device_API). WebVR was never ratified as a standard, was implemented and enabled by default in very few browsers and supported a small number of devices.
The WebVR API is a fantastic addition to the web developer's toolkit, allowing WebGL scenes to be presented in virtual reality displays such as the Oculus Rift and HTC Vive. But how do you get started with developing VR apps for the Web? This article will guide you through the basics.
## Getting started
To get started, you need:
- Supporting VR hardware.
- The cheapest option is to use a mobile device, supporting browser, and device mount (e.g. Google Cardboard). This won't be quite as good an experience as dedicated hardware, but you won't need to purchase a powerful computer or dedicated VR display.
- Dedicated hardware can be costly, but it does provide a better experience. The most WebVR-compatible hardware at the moment is the HTC VIVE, and The Oculus Rift. The front page of [webvr.info](https://webvr.info/) has some further useful information about available hardware, and what browser support them.
- A computer powerful enough to handle rendering/displaying of VR scenes using your dedicated VR Hardware, if required. To give you an idea of what you need, look at the relevant guide for the VR you are purchasing (e.g. [VIVE READY Computers](https://www.vive.com/us/ready/)).
- A supporting browser installed — the latest [Firefox Nightly](https://www.mozilla.org/en-US/firefox/channel/desktop/) or [Chrome](https://www.google.com/chrome/index.html) are your best options right now, on desktop or mobile.
Once you have everything assembled, you can test to see whether your setup works with WebVR by going to our [simple A-Frame demo](https://mdn.github.io/webvr-tests/webvr/aframe-demo/), and seeing whether the scene renders and whether you can enter VR display mode by pressing the button at the bottom right.
[A-Frame](https://aframe.io/) is by far the best option if you want to create a WebVR-compatible 3D scene quickly, without needing to understand a bunch of new JavaScript code. It doesn't however teach you how the raw WebVR API works, and this is what we'll get on to next.
## Introducing our demo
To illustrate how the WebVR API works, we'll study our raw-webgl-example, which looks a bit like this:

> **Note:** You can find the [source code of our demo](https://github.com/mdn/webvr-tests/tree/main/webvr/raw-webgl-example) on GitHub, and [view it live](https://mdn.github.io/webvr-tests/webvr/raw-webgl-example/) also.
> **Note:** If WebVR isn't working in your browser, you might need to make sure it is running through your graphics card. For example for NVIDIA cards, if you've got the NVIDIA control panel set up successfully, there will be a context menu option available — right click on Firefox, then choose _Run with graphics processor > High-performance NVIDIA processor_.
Our demo features the holy grail of WebGL demos — a rotating 3D cube. We've implemented this using raw [WebGL API](/en-US/docs/Web/API/WebGL_API) code. We won't be teaching any basic JavaScript or WebGL, just the WebVR parts.
Our demo also features:
- A button to start (and stop) our scene from being presented in the VR display.
- A button to show (and hide) VR pose data, i.e. the position and orientation of the headset, updated in real time.
When you look through the source code of [our demo's main JavaScript file](https://github.com/mdn/webvr-tests/blob/main/webvr/raw-webgl-example/webgl-demo.js), you can easily find the WebVR-specific parts by searching for the string "WebVR" in preceding comments.
> **Note:** To find out more about basic JavaScript and WebGL, consult our [JavaScript learning material](/en-US/docs/Learn/JavaScript), and our [WebGL Tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial).
## How does it work?
At this point, let's look at how the WebVR parts of the code work.
A typical (simple) WebVR app works like this:
1. {{domxref("Navigator.getVRDisplays()")}} is used to get a reference to your VR display.
2. {{domxref("VRDisplay.requestPresent()")}} is used to start presenting to the VR display.
3. WebVR's dedicated {{domxref("VRDisplay.requestAnimationFrame()")}} method is used to run the app's rendering loop at the correct refresh rate for the display.
4. Inside the rendering loop, you grab the data required to display the current frame ({{domxref("VRDisplay.getFrameData()")}}), draw the displayed scene twice — once for the view in each eye — then submit the rendered view to the display to show to the user via ({{domxref("VRDisplay.submitFrame()")}}).
In the below sections we'll look at our raw-webgl-demo in detail, and see where exactly the above features are used.
### Starting with some variables
The first WebVR-related code you'll meet is this following block:
```js
// WebVR variables
const frameData = new VRFrameData();
let vrDisplay;
const btn = document.querySelector(".stop-start");
let normalSceneFrame;
let vrSceneFrame;
const poseStatsBtn = document.querySelector(".pose-stats");
const poseStatsSection = document.querySelector("section");
poseStatsSection.style.visibility = "hidden"; // hide it initially
const posStats = document.querySelector(".pos");
const orientStats = document.querySelector(".orient");
const linVelStats = document.querySelector(".lin-vel");
const linAccStats = document.querySelector(".lin-acc");
const angVelStats = document.querySelector(".ang-vel");
const angAccStats = document.querySelector(".ang-acc");
let poseStatsDisplayed = false;
```
Let's briefly explain these:
- `frameData` contains a {{domxref("VRFrameData")}} object, created using the {{domxref("VRFrameData.VRFrameData", "VRFrameData()")}} constructor. This is initially empty, but will later contain the data required to render each frame to show in the VR display, updated constantly as the rendering loop runs.
- `vrDisplay` starts uninitialized, but will later on hold a reference to our VR headset ({{domxref("VRDisplay")}} — the central control object of the API).
- `btn` and `poseStatsBtn` hold references to the two buttons we are using to control our app.
- `normalSceneFrame` and `vrSceneFrame` start uninitialized, but later on will hold references to {{domxref("Window.requestAnimationFrame()")}} and {{domxref("VRDisplay.requestAnimationFrame()")}} calls — these will initiate the running of a normal rendering loop, and a special WebVR rendering loop; we'll explain the difference between these two later on.
- The other variables store references to different parts of the VR pose data display box, which you can see in the bottom right-hand corner of the UI.
### Getting a reference to our VR display
One of the major functions inside our code is `start()` — we run this function when the body has finished loading:
```js
// start
//
// Called when the body has loaded is created to get the ball rolling.
document.body.onload = start;
```
To begin with, `start()` retrieves a WebGL context to use to render 3D graphics into the {{htmlelement("canvas")}} element in [our HTML](https://github.com/mdn/webvr-tests/blob/main/webvr/raw-webgl-example/index.html). We then check whether the `gl` context is available — if so, we run a number of functions to set up the scene for display.
```js
function start() {
canvas = document.getElementById("glcanvas");
initWebGL(canvas); // Initialize the GL context
// WebGL setup code here
```
Next, we start the process of actually rendering the scene onto the canvas, by setting the canvas to fill the entire browser viewport, and running the rendering loop (`drawScene()`) for the first time. This is the non-WebVR — normal — rendering loop.
```js
// draw the scene normally, without WebVR - for those who don't have it and want to see the scene in their browser
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
drawScene();
```
Now onto our first WebVR-specific code. First of all, we check to see if {{domxref("Navigator.getVRDisplays")}} exists — this is the entry point into the API, and therefore good basic feature detection for WebVR. You'll see at the end of the block (inside the `else` clause) that if this doesn't exist, we log a message to indicate that WebVR 1.1 isn't supported by the browser.
```js
// WebVR: Check to see if WebVR is supported
if (navigator.getVRDisplays) {
console.log('WebVR 1.1 supported');
```
Inside our `if () { }` block, we run the {{domxref("Navigator.getVRDisplays()")}} function. This returns a promise, which is fulfilled with an array containing all the VR display devices connected to the computer. If none are connected, the array will be empty.
```js
// Then get the displays attached to the computer
navigator.getVRDisplays().then((displays) => {
```
Inside the promise `then()` block, we check whether the array length is more than 0; if so, we set the value of our `vrDisplay` variable to the 0 index item inside the array. `vrDisplay` now contains a {{domxref("VRDisplay")}} object representing our connected display!
```js
// If a display is available, use it to present the scene
if (displays.length > 0) {
vrDisplay = displays[0];
console.log('Display found');
```
> **Note:** It is unlikely that you'll have multiple VR displays connected to your computer, and this is just a simple demo, so this will do for now.
### Starting and stopping the VR presentation
Now we have a {{domxref("VRDisplay")}} object, we can use it do a number of things. The next thing we want to do is wire up functionality to start and stop presentation of the WebGL content to the display.
Continuing on with the previous code block, we now add an event listener to our start/stop button (`btn`) — when this button is clicked we want to check whether we are presenting to the display already (we do this in a fairly dumb fashion, by checking what the button [`textContent`](/en-US/docs/Web/API/Node/textContent) contains).
If the display is not already presenting, we use the {{domxref("VRDisplay.requestPresent()")}} method to request that the browser start presenting content to the display. This takes as a parameter an array of the {{domxref("VRLayerInit")}} objects representing the layers you want to present in the display.
Since the maximum number of layers you can display is currently 1, and the only required object member is the {{domxref("VRLayerInit.source")}} property (which is a reference to the {{htmlelement("canvas")}} you want to present in that layer; the other parameters are given sensible defaults — see {{domxref("VRLayerInit.leftBounds", "leftBounds")}} and {{domxref("VRLayerInit.rightBounds", "rightBounds")}})), the parameter is \[{ source: canvas }].
`requestPresent()` returns a promise that is fulfilled when the presentation begins successfully.
```js
// Starting the presentation when the button is clicked: It can only be called in response to a user gesture
btn.addEventListener('click', () => {
if (btn.textContent === 'Start VR display') {
vrDisplay.requestPresent([{ source: canvas }]).then(() => {
console.log('Presenting to WebVR display');
```
With our presentation request successful, we now want to start setting up to render content to present to the VRDisplay. First of all we set the canvas to the same size as the VR display area. We do this by getting the {{domxref("VREyeParameters")}} for both eyes using {{domxref("VRDisplay.getEyeParameters()")}}.
We then do some simple math to calculate the total width of the VRDisplay rendering area based on the eye {{domxref("VREyeParameters.renderWidth")}} and {{domxref("VREyeParameters.renderHeight")}}.
```js
// Set the canvas size to the size of the vrDisplay viewport
const leftEye = vrDisplay.getEyeParameters("left");
const rightEye = vrDisplay.getEyeParameters("right");
canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2;
canvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight);
```
Next, we {{domxref("Window.cancelAnimationFrame()", "cancel the animation loop")}} previously set in motion by the {{domxref("Window.requestAnimationFrame()")}} call inside the `drawScene()` function, and instead invoke `drawVRScene()`. This function renders the same scene as before, but with some special WebVR magic going on. The loop inside here is maintained by WebVR's special {{domxref("VRDisplay.requestAnimationFrame")}} method.
```js
// stop the normal presentation, and start the vr presentation
window.cancelAnimationFrame(normalSceneFrame);
drawVRScene();
```
Finally, we update the button text so that the next time it is pressed, it will stop presentation to the VR display.
```js
btn.textContent = 'Exit VR display';
});
```
To stop the VR presentation when the button is subsequently pressed, we call {{domxref("VRDisplay.exitPresent()")}}. We also reverse the button's text content, and swap over the `requestAnimationFrame` calls. You can see here that we are using {{domxref("VRDisplay.cancelAnimationFrame")}} to stop the VR rendering loop, and starting the normal rendering loop off again by calling `drawScene()`.
```js
} else {
vrDisplay.exitPresent();
console.log('Stopped presenting to WebVR display');
btn.textContent = 'Start VR display';
// Stop the VR presentation, and start the normal presentation
vrDisplay.cancelAnimationFrame(vrSceneFrame);
drawScene();
}
});
}
});
} else {
console.log('WebVR API not supported by this browser.');
}
}
```
Once the presentation starts, you'll be able to see the stereoscopic view displayed in the browser:

You'll learn below how the stereoscopic view is actually produced.
### Why does WebVR have its own requestAnimationFrame()?
This is a good question. The reason is that for smooth rendering inside the VR display, you need to render the content at the display's native refresh rate, not that of the computer. VR display refresh rates are greater than PC refresh rates, typically up to 90fps. The rate will be differ from the computer's core refresh rate.
Note that when the VR display is not presenting, {{domxref("VRDisplay.requestAnimationFrame")}} runs identically to {{domxref("Window.requestAnimationFrame")}}, so if you wanted, you could just use a single rendering loop, rather than the two we are using in our app. We have used two because we wanted to do slightly different things depending on whether the VR display is presenting or not, and keep things separated for ease of comprehension.
### Rendering and display
At this point, we've seen all the code required to access the VR hardware, request that we present our scene to the hardware, and start running the rending loop. Let's now look at the code for the rendering loop, and explain how the WebVR-specific parts of it work.
First of all, we begin the definition of our rendering loop function — `drawVRScene()`. The first thing we do inside here is make a call to {{domxref("VRDisplay.requestAnimationFrame()")}} to keep the loop running after it has been called once (this occurred earlier on in our code when we started presenting to the VR display). This call is set as the value of the global `vrSceneFrame` variable, so we can cancel the loop with a call to {{domxref("VRDisplay.cancelAnimationFrame()")}} once we exit VR presenting.
```js
function drawVRScene() {
// WebVR: Request the next frame of the animation
vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);
```
Next, we call {{domxref("VRDisplay.getFrameData()")}}, passing it the name of the variable that we want to use to contain the frame data. We initialized this earlier on — `frameData`. After the call completes, this variable will contain the data need to render the next frame to the VR device, packaged up as a {{domxref("VRFrameData")}} object. This contains things like projection and view matrices for rendering the scene correctly for the left and right eye view, and the current {{domxref("VRPose")}} object, which contains data on the VR display such as orientation, position, etc.
This has to be called on every frame so the rendered view is always up-to-date.
```js
// Populate frameData with the data of the next frame to display
vrDisplay.getFrameData(frameData);
```
Now we retrieve the current {{domxref("VRPose")}} from the {{domxref("VRFrameData.pose")}} property, store the position and orientation for use later on, and send the current pose to the pose stats box for display, if the `poseStatsDisplayed` variable is set to true.
```js
// You can get the position, orientation, etc. of the display from the current frame's pose
const curFramePose = frameData.pose;
const curPos = curFramePose.position;
const curOrient = curFramePose.orientation;
if (poseStatsDisplayed) {
displayPoseStats(curFramePose);
}
```
We now clear the canvas before we start drawing on it, so that the next frame is clearly seen, and we don't also see previous rendered frames:
```js
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
```
We now render the view for both the left and right eyes. First of all we need to create projection and view locations for use in the rendering. These are {{domxref("WebGLUniformLocation")}} objects, created using the {{domxref("WebGLRenderingContext.getUniformLocation()")}} method, passing it the shader program's identifier and an identifying name as parameters.
```js
// WebVR: Create the required projection and view matrix locations needed
// for passing into the uniformMatrix4fv methods below
const projectionMatrixLocation = gl.getUniformLocation(
shaderProgram,
"projMatrix",
);
const viewMatrixLocation = gl.getUniformLocation(shaderProgram, "viewMatrix");
```
The next rendering step involves:
- Specifying the viewport size for the left eye, using {{domxref("WebGLRenderingContext.viewport")}} — this is logically the first half of the canvas width, and the full canvas height.
- Specifying the view and projection matrix values to use to render the left eye — this is done using the {{domxref("WebGLRenderingContext.uniformMatrix", "WebGLRenderingContext.uniformMatrix4fv")}} method, which is passed the location values we retrieved above, and the left matrices obtained from the {{domxref("VRFrameData")}} object.
- Running the `drawGeometry()` function, which renders the actual scene — because of what we specified in the previous two steps, we will render it for the left eye only.
```js
// WebVR: Render the left eye's view to the left half of the canvas
gl.viewport(0, 0, canvas.width * 0.5, canvas.height);
gl.uniformMatrix4fv(
projectionMatrixLocation,
false,
frameData.leftProjectionMatrix,
);
gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.leftViewMatrix);
drawGeometry();
```
We now do exactly the same thing, but for the right eye:
```js
// WebVR: Render the right eye's view to the right half of the canvas
gl.viewport(canvas.width * 0.5, 0, canvas.width * 0.5, canvas.height);
gl.uniformMatrix4fv(
projectionMatrixLocation,
false,
frameData.rightProjectionMatrix,
);
gl.uniformMatrix4fv(viewMatrixLocation, false, frameData.rightViewMatrix);
drawGeometry();
```
Next we define our `drawGeometry()` function. Most of this is just general WebGL code required to draw our 3D cube. You'll see some WebVR-specific parts in the `mvTranslate()` and `mvRotate()` function calls — these pass matrices into the WebGL program that define the translation and rotation of the cube for the current frame
You'll see that we are modifying these values by the position (`curPos`) and orientation (`curOrient`) of the VR display we got from the {{domxref("VRPose")}} object. The result is that, for example, as you move or rotate your head left, the x position value (`curPos[0]`) and y rotation value (`[curOrient[1]`) are added to the x translation value, meaning that the cube will move to the right, as you'd expect when you are looking at something and then move/turn your head left.
This is a quick and dirty way to use VR pose data, but it illustrates the basic principle.
```js
function drawGeometry() {
// Establish the perspective with which we want to view the
// scene. Our field of view is 45 degrees, with a width/height
// ratio of 640:480, and we only want to see objects between 0.1 units
// and 100 units away from the camera.
perspectiveMatrix = makePerspective(45, 640.0 / 480.0, 0.1, 100.0);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
loadIdentity();
// Now move the drawing position a bit to where we want to start
// drawing the cube.
mvTranslate([
0.0 - curPos[0] * 25 + curOrient[1] * 25,
5.0 - curPos[1] * 25 - curOrient[0] * 25,
-15.0 - curPos[2] * 25,
]);
// Save the current matrix, then rotate before we draw.
mvPushMatrix();
mvRotate(cubeRotation, [0.25, 0, 0.25 - curOrient[2] * 0.5]);
// Draw the cube by binding the array buffer to the cube's vertices
// array, setting attributes, and pushing it to GL.
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesBuffer);
gl.vertexAttribPointer(vertexPositionAttribute, 3, gl.FLOAT, false, 0, 0);
// Set the texture coordinates attribute for the vertices.
gl.bindBuffer(gl.ARRAY_BUFFER, cubeVerticesTextureCoordBuffer);
gl.vertexAttribPointer(textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);
// Specify the texture to map onto the faces.
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, cubeTexture);
gl.uniform1i(gl.getUniformLocation(shaderProgram, "uSampler"), 0);
// Draw the cube.
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, cubeVerticesIndexBuffer);
setMatrixUniforms();
gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);
// Restore the original matrix
mvPopMatrix();
}
```
The next bit of the code has nothing to do with WebVR — it just updates the rotation of the cube on each frame:
```js
// Update the rotation for the next draw, if it's time to do so.
let currentTime = new Date().getTime();
if (lastCubeUpdateTime) {
const delta = currentTime - lastCubeUpdateTime;
cubeRotation += (30 * delta) / 1000.0;
}
lastCubeUpdateTime = currentTime;
```
The last part of the rendering loop involves us calling {{domxref("VRDisplay.submitFrame()")}} — now all the work has been done and we've rendered the display on the {{htmlelement("canvas")}}, this method then submits the frame to the VR display so it is displayed on there as well.
```js
// WebVR: Indicate that we are ready to present the rendered frame to the VR display
vrDisplay.submitFrame();
}
```
### Displaying the pose (position, orientation, etc.) data
In this section we'll discuss the `displayPoseStats()` function, which displays our updated pose data on each frame. The function is fairly simple.
First of all, we store the six different property values obtainable from the {{domxref("VRPose")}} object in their own variables — each one is a {{jsxref("Float32Array")}}.
```js
function displayPoseStats(pose) {
const pos = pose.position;
const orient = pose.orientation;
const linVel = pose.linearVelocity;
const linAcc = pose.linearAcceleration;
const angVel = pose.angularVelocity;
const angAcc = pose.angularAcceleration;
```
We then write out the data into the information box, updating it on every frame. We've clamped each value to three decimal places using [`toFixed()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed), as the values are hard to read otherwise.
You should note that we've used a conditional expression to detect whether the linear acceleration and angular acceleration arrays are successfully returned before we display the data. These values are not reported by most VR hardware as yet, so the code would throw an error if we did not do this (the arrays return `null` if they are not successfully reported).
```js
posStats.textContent = `Position: ` +
`x ${pos[0].toFixed(3)}, ` +
`y ${pos[1].toFixed(3)}, ` +
`z ${pos[2].toFixed(3)}`;
orientStats.textContent = `Orientation: ` +
`x ${orient[0].toFixed(3)}, ` +
`y ${orient[1].toFixed(3)}, ` +
`z ${orient[2].toFixed(3)}`;
linVelStats.textContent = `Linear velocity: ` +
`x ${linVel[0].toFixed(3)}, ` +
`y ${linVel[1].toFixed(3)}, ` +
`z ${linVel[2].toFixed(3)}`;
angVelStats.textContent = `Angular velocity: ` +
`x ${angVel[0].toFixed(3)}, ` +
`y ${angVel[1].toFixed(3)}, ` +
`z ${angVel[2].toFixed(3)}`;
if (linAcc) {
linAccStats.textContent = `Linear acceleration: ` +
`x ${linAcc[0].toFixed(3)}, ` +
`y ${linAcc[1].toFixed(3)}, ` +
`z ${linAcc[2].toFixed(3)}`;
} else {
linAccStats.textContent = 'Linear acceleration not reported';
}
if (angAcc) {
angAccStats.textContent = `Angular acceleration: ` +
`x ${angAcc[0].toFixed(3)}, ` +
`y ${angAcc[1].toFixed(3)}, ` +
`z ${angAcc[2].toFixed(3)}`;
} else {
angAccStats.textContent = 'Angular acceleration not reported';
}
}
```
## WebVR events
The WebVR spec features a number of events that are fired, allowing our app code to react to changes in the state of the VR display (see [Window events](/en-US/docs/Web/API/WebVR_API#window_events)). For example:
- {{domxref("Window/vrdisplaypresentchange_event", "vrdisplaypresentchange")}} — Fires when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa.
- {{domxref("Window.vrdisplayconnect_event", "vrdisplayconnect")}} — Fires when a compatible VR display has been connected to the computer.
- {{domxref("Window.vrdisplaydisconnect_event", "vrdisplaydisconnect")}} — Fires when a compatible VR display has been disconnected from the computer.
To demonstrate how they work, our simple demo includes the following example:
```js
window.addEventListener("vrdisplaypresentchange", (e) => {
console.log(
`Display ${e.display.displayId} presentation has changed. Reason given: ${e.reason}.`,
);
});
```
As you can see, the {{domxref("VRDisplayEvent", "event object")}} provides two useful properties — {{domxref("VRDisplayEvent.display")}}, which contains a reference to the {{domxref("VRDisplay")}} the event was fired in response to, and {{domxref("VRDisplayEvent.reason")}}, which contains a human-readable reason why the event was fired.
This is a very useful event; you could use it to handle cases where the display gets disconnected unexpectedly, stopping errors from being thrown and making sure the user is aware of the situation. In Google's Webvr.info presentation demo, the event is used to run an [`onVRPresentChange()` function](https://github.com/toji/webvr.info/blob/master/samples/03-vr-presentation.html#L174), which updates the UI controls as appropriate and resizes the canvas.
## Summary
This article has given you the very basics of how to create a simple WebVR 1.1 app, to help you get started.
| 0 |
data/mdn-content/files/en-us/web/api/webvr_api | data/mdn-content/files/en-us/web/api/webvr_api/concepts/index.md | ---
title: WebVR concepts
slug: Web/API/WebVR_API/Concepts
page-type: guide
---
{{APIRef("WebVR API")}}{{deprecated_header}}
> **Note:** WebVR API is replaced by [WebXR API](/en-US/docs/Web/API/WebXR_Device_API). WebVR was never ratified as a standard, was implemented and enabled by default in very few browsers and supported a small number of devices.
This article discusses some of the concepts and theory behind virtual reality (VR). If you are a newcomer to the area, it is worthwhile getting an understanding of these topics before you start diving into code.
## The history of VR
Virtual reality is nothing new — the concept goes way further back than the Oculus Rift Kickstarter campaign of 2012. People have been experimenting with it for decades.
In 1939 the [View-Master device](https://en.wikipedia.org/wiki/View-Master) was created, allowing people to see 3D pictures. The device displayed images stored on cardboard disks containing stereoscopic 3D pairs of small color photographs. After years of development the military got interested in using such technology, and Project Headsight was born in 1961 — this involved a helmet incorporating a video screen with a head-tracking system.
There were various experiments conducted over the next few decades, but it wasn't restricted to science labs and battlefields anymore. Eventually pop culture took over with movie directors showing their visions of virtual reality. Movies like Tron (1982) and The Matrix (1999) were created, where people could transfer themselves into a whole new cyber world or were trapped in one without even knowing, accepting it as the real world.
The first VR gaming attempts were big and expensive — in 1991 Virtuality Group created a VR-ready arcade machine with goggles and ported popular titles like Pac-Man to virtual reality. Sega introduced their VR glasses at the Consumer Electronics Show in 1993. Companies were experimenting, but the market and consumers weren't convinced — we had to wait until 2012 to see a real example of a successful VR project.
### VR in recent times
So what's new? Virtual Reality hardware needs to deliver high-precision, low-latency data to deliver an acceptable user experience; computers running VR applications need to be powerful enough to handle all this information. It has not been until recently that such accuracy and power has been available at an affordable cost, if at all. Early VR prototypes cost tens of thousands of dollars, whereas more recent headsets such as the [HTC VIVE](https://www.vive.com/uk/) and [Oculus Rift](https://www.oculus.com/rift/) are available for hundreds of dollars, and cheaper solutions are available — mobile device-based solutions like [Gear VR](https://www.samsung.com/global/galaxy/what-is/gear-vr/) and [Google Cardboard](https://arvr.google.com/cardboard/).
On the software side, Valve has created [SteamVR](https://store.steampowered.com/search/?category1=993) software, which is compatible with the VIVE and other solutions, and serves to provide access to software, such as a usable VR UI.
The technology itself is here, and the more expensive headsets will only get cheaper over time so more people can experience virtual reality on their own in the future.
### Input devices
Handling input for virtual reality applications is an interesting topic — it's a totally new experience for which dedicated user interfaces have to be designed. There are various approaches right now from classic keyboard and mouse, to new ones like Leap Motion and the VIVE controllers. It's a matter of trial and error to see what works in given situations and what inputs fit best for your type of game.
## VR Hardware setup
There are two main types of setup, mobile or computer-connected. Their minimum hardware set ups are as follows:
- Mobile: A Head-mounted display (HMD) is created using a smartphone — which acts as the VR display — mounted in a VR mount such as Google Cardboard, which contains the required lenses to provide stereoscopic vision of what is projected on the mobile screen.
- Computer-connected: A VR setup is connected to your computer — this consists of a Head Mounted Display (HMD) containing a high resolution landscape-oriented screen onto which the visuals for both the left and right eye are displayed, which also includes a lens for each eye to promote separation of the left and right eye scene (stereoscopic vision.) The setup also includes a separate position sensor that works out the position/orientation/velocity/acceleration of your head and constantly passes that information the computer. 
> **Note:** Computer-connected systems sometimes don't include a position sensor, but they usually do.
Other hardware that complements the VR experience includes:
- **A hand recognition sensor**: A sensor that tracks the position and movement of your hand, allowing it to become an interesting controller, and an object in VR gameworlds. The most advanced to date is the [Leap Motion](https://www.ultraleap.com/), which works with the computer (connected to the Oculus Rift) and can also work connected to a mobile device (the latter is in an experimental phase.)
- **A gamepad**: We can configure an XBox controller or similar to work as a keyboard in the browser — this offers further possibilities of interaction with a VR webpage. There are some gamepads that work with a mobile setup but these are connected via Bluetooth so don't work with WebVR.
- **An eye tracking sensor (experimental)**: The FOVE project is the first headset that reads subtle eye movements.
- **A facial expression tracker (experimental)**: Researchers at the University of Southern California and Facebook's Oculus division have been testing new ways of tracking facial expressions and transferring them to a virtual character.
- **A more complex positional sensor system**: As an example, the HTC VIVE features two position sensors that sit in opposite corners of a space, mapping it all out and allowing VR experiences to be enjoyed in spaces of up to 5m x 5m.
## Position and orientation, velocity and acceleration
As mentioned above, the position sensor detects information concerning the HMD and constantly outputs it, allowing you to continually update a scene according to head movement, rotation, etc. But what exactly is the information?

The output information falls into four categories:
1. Position — The position of the HMD along three axes in a 3D coordinate space. x is to the left and right, y is up and down, and z is towards and away from the position sensor. In WebVR, the x, y, and z coordinates are represented by the array contained in {{domxref("VRPose.position")}}.
2. Orientation — The rotation of the HMD around three axes in a 3D coordinate space. Pitch is rotation around the x axis, yaw is rotation around the y axis, and roll is rotation around the z axis. In WebVR, the pitch, yaw, and roll are represented by the first three elements of the array contained in {{domxref("VRPose.orientation")}}.
3. Velocity — There are two types of velocity to consider in VR:
- Linear — The speed along any one of the axes that the HMD is traveling. This information can be accessed using {{domxref("VRPose.linearVelocity")}}.
- Angular — The speed at which the HMD is rotating around any one of the axes. This information can be accessed using {{domxref("VRPose.angularVelocity")}}.
4. Acceleration — There are two types of acceleration to consider in VR:
- Linear — The acceleration of travel along any one of the axes that the HMD is traveling. This information can be accessed using {{domxref("VRPose.linearAcceleration")}}.
- Angular — The acceleration of rotation of the HMD around any one of the axes. This information can be accessed using {{domxref("VRPose.angularAcceleration")}}.
## Field of view
The field of view (FOV) is the area that each of the user's eyes can reasonably be expected to see. It roughly takes the form of a pyramid shape, laid down on one side, with the apex inside the user's head, and the rest of the pyramid emanating from the user's eye. Each eye has its own FOV, one slightly overlapping the other.

The FOV is defined by the following values:
- {{domxref("VRFieldOfView.upDegrees")}}: The number of degrees upwards that the field of view extends in.
- {{domxref("VRFieldOfView.rightDegrees")}}: The number of degrees to the right that the field of view extends in.
- {{domxref("VRFieldOfView.downDegrees")}}: The number of degrees downwards that the field of view extends in.
- {{domxref("VRFieldOfView.leftDegrees")}}: The number of degrees to the left that the field of view extends in.
- zNear, defined by {{domxref("VRDisplay.depthNear")}}: The distance from the middle of the user's head to the start of the visible FOV.
- zFar, defined by {{domxref("VRDisplay.depthFar")}}: The distance from the middle of the user's head to the end of the visible FOV.
The default values for these properties will differ slightly by VR hardware, although they tend to be around 53° up and down, and 47° left and right, with zNear and zFar coming in at around 0.1m and 10000m respectively.
> **Note:** The user can potentially see all the way around them, which is a brand new concept for apps and games. Try to give people a reason to look around and see what's behind them — make them reach out and find things that are not visible at the very beginning. Describe what's behind their backs.
## Concepts for VR apps
This section discusses concepts to be aware of when developing VR apps that you've probably not had to consider before when developing regular apps for mobile or desktop.
### Stereoscopic vision
Stereoscopic vision is the normal vision humans and (most) animals have — the perception of two slightly differing images (one from each eye) as a single image. This results in depth perception, helping us to see the world in glorious 3D. To recreate this in VR apps, you need to render two very slightly different views side by side, which will be taken in by the left and right eyes when the user is using the HMD.

### Head tracking
The primary technology used to make you feel present in a 360º scene, thanks to the gyroscope, accelerometer, and magnetometer (compass) included in the HMD.
It has primary relevance because it makes our eyes believe we are in front of a spherical screen, giving users realistic immersion inside the app canvas.
### Eye strain
A term commonly used in VR because it is a major handicap of using an HMD — we are constantly fooling the eye with what we are showing in the app canvas, and this leads to the eyes doing a lot more work than they normally would, so using VR apps for any extended period of time can lead to eye strain.
To minimize this unwanted effect, we need to:
- Avoid focusing on different depths (e.g. avoid using a lot of particles with different depths.)
- Avoid eye convergence (e.g. if you have an object that comes towards the camera your eyes will follow and converge on it.)
- Use darker backgrounds with more subdued colors where possible; a bright screen will make the eyes more tired.
- Avoid rapid brightness changes.
- Avoid presenting the user with large amounts of text to read. You should also be careful with the distance between the eyes/camera and the text to read. 0.5m is uncomfortable, whereas at more than 2m the stereo effect starts to break down, so somewhere in between is advisable.
- Be careful with the distance between objects and the camera in general. Oculus recommends 0.75m as a minimum distance of focus.
- Use a pointer if the user needs to interact with an object in the scene — this will help them point to it correctly with less effort.
In general, the path of least visual effort will give the user a less tiring experience.
### Motion sickness
If developers do not take utmost care, VR apps can actually cause their users to feel sick. This effect is produced when the stimuli their eyes are receiving is not what the body expects to receive.
To avoid bringing on motion sickness in our users (or at least minimize the effects), we need to:
- Always maintain head tracking (this is the most important of all, especially if it occurs in middle of the experience.)
- Use constant velocity; avoid acceleration or deceleration camera movements (use linear acceleration, and avoid easing if you can.)
- Keep the frame rate up (less than 30fps is uncomfortable.)
- Avoid sharp and/or unexpected camera rotations.
- Add fixed points of reference for fixed objects (otherwise the user will believe they are on the move.)
- Do not use Depth of Field or Motion Blur post processing because you do not know where the eyes will focus.
- Avoid brightness changes (use low frequency textures or fog effects to create smooth lighting transitions).
Overall your eyes should not send signals to the brain that cause reflex actions in other parts of the body.
### Latency
Latency is the time between the physical head movement and the visual display reaching the user's eyes from the screen of an HMD being updated. This is one of the most critical factors in providing a realistic experience. Humans can detect very small delays — we need to keep the latency below 20 milliseconds if they are to be imperceptible (for example a 60Hz monitor has a 16 ms response.)
The Oculus Rift headset has a latency of 20 ms or less, but with mobile device-based setups it will depend heavily on the smartphone CPU power and other capabilities.
### Frame rate (Frames per second / FPS)
Based on the Wikipedia definition, frame rate is the frequency at which an imaging device produces unique consecutive images, called frames. A rate of 60fps is an acceptable rate for a smooth user experience, but depending on the performance of the machine the app is running on, or the complexity of the content you want to show, it can drastically lower. Less than 30fps is generally considered jittery, and annoying to the user.
One of the most difficult tasks is to maintain a constant and high frame rate value, so we must optimize our code to make it as efficient as possible. It is preferable to have a decent frame rate that doesn't constantly or suddenly change; for this you need to as few necessary objects moving into the scene as possible and (in the case of WebGL) try to reduce draw calls.
### Interpupillary distance (IPD)
Based on the Wikipedia definition, IPD is the distance between the centers of the pupils of the two eyes. IPD is critical for the design of binocular viewing systems, where both eye pupils need to be positioned within the exit pupils of the viewing system.
Interpupillary distance (IPD) can be calculated using {{domxref("VREyeParameters.offset")}} in WebVR, which is equal to half the IPD.
This value is returned by the HMD and its value may be around 60 to 70 mm; in the case of some HMDs like Oculus Rift's, you can set your own IPD. Normally we don't change this value but you can play with it to change the scale of the entire scene. For example, if your IPD is set to 6000 mm, the user would view the scene like a giant looking at a Lilliputian world.
### Degrees of Freedom (DoF)
DoF refers to the movement of a rigid body inside space. There is no uniformity in creating acronyms for this term — we can find references to 3DoF in the context of sensors that detect only rotational head tracking, and 6DoF when an input allows us to control position and orientation simultaneously. We even sometimes find 9DoF references when the hardware contains three sensors like gyroscope, accelerometer and magnetometer, but the results of the 3 x 3DoF values will actually return a 6 degrees of freedom tracking.
DoF is directly related to the tracking of the user's head movement.
### Cone of focus
Although our field of view is much larger (approximately 180º), we need to be aware that only in a small portion of that field can you perceive symbols (the center 60º) or read text (the center 10º). If you do not have an eye tracking sensor we assume that the center of the screen is where the user is focusing their eyes.
This limitation is important to consider when deciding where to place visuals on the app canvas — too far toward the edge of the cone of focus can lead to eye strain much more quickly. Read very interesting post [Quick VR Mockups with Illustrator](https://blog.mozvr.com/quick-vr-prototypes/).
### 3D Positional Audio
3D positional audio refers to a group of effects that manipulate audio to simulate how it would sound in a three dimensional space.
This directly related to the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API), which allows us to place sounds on objects we have in the canvas or launch audio depending on the part of the scene the user is traveling towards or looking at.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/css_typed_om_api/index.md | ---
title: CSS Typed Object Model API
slug: Web/API/CSS_Typed_OM_API
page-type: web-api-overview
browser-compat:
- api.CSSStyleValue
- api.StylePropertyMap
- api.CSSUnparsedValue
- api.CSSKeywordValue
---
{{DefaultAPISidebar("CSS Typed Object Model API")}}
The CSS Typed Object Model API simplifies CSS property manipulation by exposing CSS values as typed JavaScript objects rather than strings. This not only simplifies CSS manipulation, but also lessens the negative impact on performance as compared to {{domxref('HTMLElement.style')}}.
Generally, CSS values can be read and written in JavaScript as strings, which can be slow and cumbersome. CSS Typed Object Model API provides interfaces to interact with underlying values, by representing them with specialized JS objects that can be manipulated and understood more easily and more reliably than string parsing and concatenation. This is easier for authors (for example, numeric values are reflected with actual JS numbers, and have unit-aware mathematical operations defined for them). It is also generally faster, as values can be directly manipulated and then cheaply translated back into underlying values without having to both build and parse strings of CSS.
CSS Typed OM both allows for the performant manipulation of values assigned to CSS properties while enabling maintainable code that is both more understandable and easier to write.
## Interfaces
### `CSSStyleValue`
The {{domxref('CSSStyleValue')}} interface of the CSS Typed Object Model API is the base class of all CSS values accessible through the Typed OM API. An instance of this class may be used anywhere a string is expected.
- {{domxref('CSSStyleValue/parse_static', 'CSSStyleValue.parse()')}}
- : The parse() method of the CSSStyleValue interface allows a CSSNumericValue to be constructed from a CSS string. It sets a specific CSS property to the specified values and returns the first value as a CSSStyleValue object.
- {{domxref('CSSStyleValue.parseAll_static', 'CSSStyleValue.parseAll()')}}
- : The parseAll() method of the CSSStyleValue interface sets all occurrences of a specific CSS property to the specified value and returns an array of CSSStyleValue objects, each containing one of the supplied values.
### `StylePropertyMap`
The {{domxref('StylePropertyMap')}} interface of the CSS Typed Object Model API provides a representation of a CSS declaration block that is an alternative to CSSStyleDeclaration.
- {{domxref('StylePropertyMap.set()')}}
- : Method of StylePropertyMap interface that changes the CSS declaration with the given property to the value given.
- {{domxref('StylePropertyMap.append()')}}
- : Method that adds a new CSS declaration to the StylePropertyMap with the given property and value.
- {{domxref('StylePropertyMap.delete()')}}
- : Method that removes the CSS declaration with the given property from the StylePropertyMap.
- {{domxref('StylePropertyMap.clear()')}}
- : Method that removes all declarations in the StylePropertyMap.
### `CSSUnparsedValue`
The {{domxref('CSSUnparsedValue')}} interface of the CSS Typed Object Model API represents property values that reference custom properties. It consists of a list of string fragments and variable references.
- {{domxref("CSSUnparsedValue.CSSUnparsedValue", "CSSUnparsedValue()")}} constructor
- : Creates a new CSSUnparsedValue object which represents property values that reference custom properties.
- {{domxref('CSSUnparsedValue.entries()')}}
- : Method returning an array of a given object's own enumerable property \[key, value] pairs in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
- {{domxref('CSSUnparsedValue.forEach()')}}
- : Method executing a provided function once for each element of the CSSUnparsedValue.
- {{domxref('CSSUnparsedValue.keys()')}}
- : Method returning a new _array iterator_ object that contains the keys for each index in the array.
### `CSSKeywordValue` Serialization
The {{domxref('CSSKeywordValue')}} interface of the CSS Typed Object Model API creates an object to represent CSS keywords and other identifiers.
- {{domxref("CSSKeywordValue.CSSKeywordValue", "CSSKeywordValue()")}} constructor
- : Constructor creates a new {{domxref("CSSKeywordValue.CSSKeywordValue", "CSSKeywordValue()")}} object which represents CSS keywords and other identifiers.
- {{domxref('CSSKeywordValue.value()')}}
- : Property of the CSSKeywordValue interface returning or setting the value of the CSSKeywordValue.
## CSSStyleValue Interfaces
CSSStyleValue is the base class through which all CSS values are expressed. Subclasses include:
- {{domxref('CSSImageValue')}} objects
- : An interface representing values for properties that take an image, for example [`background-image`](/en-US/docs/Web/CSS/background-image), [`list-style-image`](/en-US/docs/Web/CSS/list-style-image), or [`border-image-source`](/en-US/docs/Web/CSS/border-image-source).
- {{domxref('CSSKeywordValue')}}
- : An interface which creates an object to represent CSS keywords and other identifiers. When used where a string is expected, it will return the value of CSSKeyword.value.
- {{domxref('CSSMathValue')}}
- : A tree of subclasses representing numeric values that are more complicated than a single value and unit, including:
- {{domxref('CSSMathInvert')}} - represents a CSS {{cssxref("calc","calc()")}} value used as `calc(1 / <value>)`.
- {{domxref('CSSMathMax')}} - represents the CSS {{cssxref("max","max()")}} function.
- {{domxref('CSSMathMin')}} - represents the CSS {{cssxref("min","min()")}} function.
- {{domxref('CSSMathNegate')}} - negates the value passed into it.
- {{domxref('CSSMathProduct')}} - represents the result obtained by calling {{domxref('CSSNumericValue.add','add()')}}, {{domxref('CSSNumericValue.sub','sub()')}}, or {{domxref('CSSNumericValue.toSum','toSum()')}} on {{domxref('CSSNumericValue')}}.
- {{domxref('CSSMathSum')}} - represents the result obtained by calling {{domxref('CSSNumericValue.add','add()')}}, {{domxref('CSSNumericValue.sub','sub()')}}, or {{domxref('CSSNumericValue.toSum','toSum()')}} on {{domxref('CSSNumericValue')}}.
- {{domxref('CSSNumericValue')}}
- : An interface representing operations that all numeric values can perform, including:
- {{domxref('CSSNumericValue.add')}} - Adds supplied numbers to the `CSSNumericValue`.
- {{domxref('CSSNumericValue.sub')}} - Subtracts supplied numbers to the `CSSNumericValue`.
- {{domxref('CSSNumericValue.mul')}} - Multiplies supplied numbers to the `CSSNumericValue`.
- {{domxref('CSSNumericValue.div')}} - Divides a supplied number by other numbers, throwing an error if 0.
- {{domxref('CSSNumericValue.min')}} - Returns the minimum value passed
- {{domxref('CSSNumericValue.max')}} - Returns the maximum value passed
- {{domxref('CSSNumericValue.equals')}} - Returns true if all the values are the exact same type and value, in the same order. Otherwise, false
- {{domxref('CSSNumericValue.to')}} - Converts `value` into another one with the specified _unit._
- {{domxref('CSSNumericValue.toSum')}}
- {{domxref('CSSNumericValue.type')}}
- {{domxref('CSSNumericValue/parse_static', 'CSSNumericValue.parse')}} - Returns a number parsed from a CSS string
- {{domxref('CSSPositionValue')}}
- : Represents values for properties that take a position, for example object-position.
- {{domxref('CSSTransformValue')}}
- : An interface representing a list of [`transform`](/en-US/docs/Web/CSS/transform) list values. They "contain" one or more {{domxref('CSSTransformComponent')}}s, which represent individual `transform` function values.
- {{domxref('CSSUnitValue')}}
- : An interface representing numeric values that can be represented as a single unit, or a named number and percentage.
- {{domxref('CSSUnparsedValue')}}
- : Represents property values that reference [custom properties](/en-US/docs/Web/CSS/--*). It consists of a list of string fragments and variable references.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API)
- [Using the CSS Typed Object Model](/en-US/docs/Web/API/CSS_Typed_OM_API/Guide)
- [CSS Houdini](/en-US/docs/Web/API/Houdini_APIs)
| 0 |
data/mdn-content/files/en-us/web/api/css_typed_om_api | data/mdn-content/files/en-us/web/api/css_typed_om_api/guide/index.md | ---
title: Using the CSS Typed Object Model
slug: Web/API/CSS_Typed_OM_API/Guide
page-type: guide
---
{{DefaultAPISidebar("CSS Typed Object Model API")}}
The **[CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Typed_OM_API)** exposes CSS values as typed JavaScript objects to allow their performant manipulation.
Converting [CSS Object Model](/en-US/docs/Web/API/CSS_Object_Model) value strings into meaningfully-typed JavaScript representations and back (via {{domxref("HTMLElement.style")}}) can incur a significant performance overhead.
The CSS Typed OM makes CSS manipulation more logical and performant by providing object features (rather than CSSOM string manipulation), providing access to types, methods, and an object model for CSS values.
This article provides an introduction to all of its main features.
## computedStyleMap()
With the CSS Typed OM API, we can access all the CSS properties and values — including custom properties — that are impacting an element. Let's see how this works by creating our first example, which explores {{domxref('Element.computedStyleMap()', 'computedStyleMap()')}}.
### Getting all the properties and values
#### HTML
We start with some HTML: a paragraph with a link, as well as a definition list to which we will add all the CSS Property / Value pairs.
```html
<p>
<a href="https://example.com">Link</a>
</p>
<dl id="regurgitation"></dl>
```
#### JavaScript
We add JavaScript to grab our unstyled link and return back a definition list of all the default CSS property values impacting the link using `computedStyleMap()`.
```js
// Get the element
const myElement = document.querySelector("a");
// Get the <dl> we'll be populating
const stylesList = document.querySelector("#regurgitation");
// Retrieve all computed styles with computedStyleMap()
const defaultComputedStyles = myElement.computedStyleMap();
// Iterate through the map of all the properties and values, adding a <dt> and <dd> for each
for (const [prop, val] of defaultComputedStyles) {
// properties
const cssProperty = document.createElement("dt");
cssProperty.appendChild(document.createTextNode(prop));
stylesList.appendChild(cssProperty);
// values
const cssValue = document.createElement("dd");
cssValue.appendChild(document.createTextNode(val));
stylesList.appendChild(cssValue);
}
```
The `computedStyleMap()` method returns a {{domxref('StylePropertyMapReadOnly')}} object containing the [`size`](/en-US/docs/Web/API/StylePropertyMapReadOnly/size) property, which indicates how many properties are in the map. We iterate through the style map, creating a [`<dt>`](/en-US/docs/Web/HTML/Element/dt) and [`<dd>`](/en-US/docs/Web/HTML/Element/dd) for each property and value respectively.
#### Result
In [browsers that support `computedStyleMap()`](/en-US/docs/Web/API/Element/computedStyleMap#browser_compatibility), you'll see a list of all the CSS properties and values. In other browsers, you'll just see a link.
{{EmbedLiveSample("Getting_all_the_properties_and_values", 120, 300)}}
Did you realize how many default CSS properties a link had? Update the JavaScript on line 2 to select the {{htmlelement("p")}} rather than the {{htmlelement("a")}}. You'll notice a difference in the [`margin-top`](/en-US/docs/Web/CSS/margin-top) and [`margin-bottom`](/en-US/docs/Web/CSS/margin-bottom) default computed values.
### .get() method / custom properties
Let's update our example to only retrieve a few properties and values. Let's start by adding some CSS to our example, including a custom property and an inheritable property:
```css
p {
font-weight: bold;
}
a {
--color: red;
color: var(--color);
}
```
Instead of getting _all_ the properties, we create an array of properties of interest and use the {{domxref('StylePropertyMapReadOnly.get()')}} method to get each of their values:
```html hidden
<p>
<a href="https://example.com">Link</a>
</p>
<dl id="regurgitation"></dl>
```
```js
// Get the element
const myElement = document.querySelector("a");
// Get the <dl> we'll be populating
const stylesList = document.querySelector("#regurgitation");
// Retrieve all computed styles with computedStyleMap()
const allComputedStyles = myElement.computedStyleMap();
// Array of properties we're interested in
const ofInterest = ["font-weight", "border-left-color", "color", "--color"];
// iterate through our properties of interest
for (const value of ofInterest) {
// Properties
const cssProperty = document.createElement("dt");
cssProperty.appendChild(document.createTextNode(value));
stylesList.appendChild(cssProperty);
// Values
const cssValue = document.createElement("dd");
cssValue.appendChild(document.createTextNode(allComputedStyles.get(value)));
stylesList.appendChild(cssValue);
}
```
{{EmbedLiveSample(".get_method_custom_properties", 120, 300)}}
We included {{cssxref('border-left-color')}} to demonstrate that, had we included all the properties, every value that defaults to [`currentcolor`](/en-US/docs/Web/CSS/color_value) (including {{cssxref('caret-color')}}, {{cssxref('outline-color')}}, {{cssxref('text-decoration-color')}}, {{cssxref('column-rule-color')}}, etc.) would return `rgb(255 0 0)`. The link has inherited `font-weight: bold;` from the paragraph's styles, listing it as `font-weight: 700`. Custom properties, like our `--color: red`, are properties. As such, they are accessible via `get()`.
You'll note that custom properties retain the value as written in the stylesheet, whereas computed styles will be listed as the computed value — {{cssxref('color')}} was listed as an [`rgb()`](/en-US/docs/Web/CSS/color_value) value and the {{cssxref('font-weight')}} returned was `700` even though we use a {{cssxref('<color>', 'named color')}} and the `bold` keyword.
### CSSUnitValue and CSSKeywordValue
The power of the CSS Typed OM is that values are separate from units; parsing and concatenating string values may become be a thing of the past. Every CSS property in a style map has a value. If the value is a keyword, the object returned is a [`CSSKeywordValue`](/en-US/docs/Web/API/CSSKeywordValue). If the value is numeric, a [`CSSUnitValue`](/en-US/docs/Web/API/CSSUnitValue) is returned.
`CSSKeywordValue` is a class that defines keywords like `inherit`, `initial`, `unset`, and other strings you don't quote, such as `auto` and `grid`. This subclass gives you a `value` property via {{domxref("cssKeywordValue.value")}}.
`CSSUnitValue` is returned if the value is a unit type. It is a class that defines numbers with units of measurement like `20px`, `40%`, `200ms`, or `7`. It is returned with two properties: a `value` and a `unit`. With this type we can access the numeric value — {{domxref('cssUnitValue.value')}} — and its unit — {{domxref('cssUnitValue.unit')}}.
Let's write a plain paragraph, apply no styles, and inspect a few of its CSS properties by returning a table with the unit and value:
```html
<p>
This is a paragraph with some content. Open up this example in Codepen or
JSFiddle, and change some features. Try adding some CSS, such as a width
for this paragraph, or adding a CSS property to the ofInterest array.
</p>
<table id="regurgitation">
<thead>
<tr>
<th>Property</th>
<th>Value</th>
<th>Unit</th>
</tr>
</table>
```
For each property of interest, we list the name of the property, use `.get(propertyName).value` to return the value, and, if the object returned by the `get()` is a `CSSUnitValue`, list the unit type we retrieve with `.get(propertyName).unit`.
```js
// Get the element we're inspecting
const myElement = document.querySelector("p");
// Get the table we'll be populating
const stylesTable = document.querySelector("#regurgitation");
// Retrieve all computed styles with computedStyleMap()
const allComputedStyles = myElement.computedStyleMap();
// Array of properties we're interested in
const ofInterest = [
"padding-top",
"margin-bottom",
"font-size",
"font-stretch",
"animation-duration",
"animation-iteration-count",
"width",
"height",
];
// Iterate through our properties of interest
for (const value of ofInterest) {
// Create a row
const row = document.createElement("tr");
// Add the name of the property
const cssProperty = document.createElement("td");
cssProperty.appendChild(document.createTextNode(value));
row.appendChild(cssProperty);
// Add the unitless value
const cssValue = document.createElement("td");
// Shrink long floats to 1 decimal point
let propVal = allComputedStyles.get(value).value;
propVal = propVal % 1 ? propVal.toFixed(1) : propVal;
cssValue.appendChild(document.createTextNode(propVal));
row.appendChild(cssValue);
// Add the type of unit
const cssUnit = document.createElement("td");
cssUnit.appendChild(
document.createTextNode(allComputedStyles.get(value).unit),
);
row.appendChild(cssUnit);
// Add the row to the table
stylesTable.appendChild(row);
}
```
{{EmbedLiveSample("CSSUnitValue_and_CSSKeywordValue", 120, 300)}}
For those of you using a non-supporting browser, the above output should look something like this:
| Property | Value | Unit |
| ---------------------------------------- | ----- | ----------- |
| {{cssxref("padding-top")}} | 0 | `px` |
| {{cssxref("margin-bottom")}} | 16 | `px` |
| {{cssxref("font-size")}} | 16 | `px` |
| {{cssxref("font-stretch")}} | 100 | `%` |
| {{cssxref("animation-duration")}} | 0 | `px` |
| {{cssxref("animation-iteration-count")}} | 1 | _number_ |
| {{cssxref("width")}} | auto | _undefined_ |
| {{cssxref("height")}} | auto | _undefined_ |
You'll note the {{cssxref('<length>')}} unit returned is `px`, the {{cssxref('<percentage>')}} unit returned is `percent`, the {{cssxref('<time>')}} unit is `s` for 'seconds', and the unitless {{cssxref('<number>')}} unit is `number`.
We didn't declare a {{cssxref('width')}} or a {{cssxref('height')}} for the paragraph, both of which default to `auto` and therefore return a [`CSSKeywordValue`](/en-US/docs/Web/API/CSSKeywordValue) instead of a [`CSSUnitValue`](/en-US/docs/Web/API/CSSUnitValue). `CSSKeywordValue`s do not have a unit property, so in these cases our `get().unit` returns `undefined`.
Had the `width` or `height` been defined in a `<length>` or `<percent>`, the [`CSSUnitValue`](/en-US/docs/Web/API/CSSUnitValue) unit would have been `px` or `percent` respectively.
There are other types available:
- An [`<image>`](/en-US/docs/Web/CSS/image) will return a {{domxref('CSSImageValue')}}.
- A [`<color>`](/en-US/docs/Web/CSS/color_value) would return a {{domxref('CSSStyleValue')}}.
- A {{cssxref('transform')}} returns a `CSSTransformValue`.
- A [custom property](/en-US/docs/Web/CSS/--*) returns a {{domxref('CSSUnparsedValue')}}.
You can use a `CSSUnitValue` or `CSSKeywordValue` to create other objects.
## CSSStyleValue
The `CSSStyleValue` interface of the [CSS Typed Object Model API](/en-US/docs/Web/API/CSS_Object_Model#css_typed_object_model) is the base class of all CSS values accessible through the Typed OM API, including {{domxref('CSSImageValue')}}, {{domxref('CSSKeywordValue')}}, {{domxref('CSSNumericValue')}}, {{domxref('CSSPositionValue')}}, {{domxref('CSSTransformValue')}}, and {{domxref('CSSUnparsedValue')}}.
It has two methods:
- {{domxref("CSSStyleValue/parse_static", "CSSStyleValue.parse()")}}
- {{domxref("CSSStyleValue/parseAll_static", "CSSStyleValue.parseAll()")}}
As noted above, `StylePropertyMapReadOnly.get('--customProperty')` returns a {{domxref('CSSUnparsedValue')}}. We can parse `CSSUnparsedValue` object instances with the inherited {{domxref('CSSStyleValue/parse_static', 'CSSStyleValue.parse()')}} and {{domxref('CSSStyleValue/parseAll_static', 'CSSStyleValue.parseAll()')}} methods.
Let's examine a CSS example with several custom properties, transforms, `calc()`s, and other features. We'll take a look at what their types are by employing short JavaScript snippets outputting to {{domxref("console/log_static", "console.log()")}}:
```css
:root {
--mainColor: hsl(198 43% 42%);
--black: hsl(0 0% 16%);
--white: hsl(0 0% 97%);
--unit: 1.2rem;
}
button {
--mainColor: hsl(198 100% 66%);
display: inline-block;
padding: var(--unit) calc(var(--unit) * 2);
width: calc(30% + 20px);
background: no-repeat 5% center url(magicwand.png) var(--mainColor);
border: 4px solid var(--mainColor);
border-radius: 2px;
font-size: calc(var(--unit) * 2);
color: var(--white);
cursor: pointer;
transform: scale(0.95);
}
```
Let's add the class to a button (a button which does nothing).
```html
<button>Styled Button</button>
```
```js hidden
// get the element
const button = document.querySelector("button");
// Retrieve all computed styles with computedStyleMap()
const allComputedStyles = button.computedStyleMap();
// CSSMathSum Example
let btnWidth = allComputedStyles.get("width");
console.log(btnWidth); // CSSMathSum
console.log(btnWidth.values); // CSSNumericArray {0: CSSUnitValue, 1: CSSUnitValue, length: 2}
console.log(btnWidth.operator); // 'sum'
// CSSTransformValue
let transform = allComputedStyles.get("transform");
console.log(transform); // CSSTransformValue {0: CSSScale, 1: CSSTranslate, length: 2, is2D: true}
console.log(transform.length); // 1
console.log(transform[0]); // CSSScale {x: CSSUnitValue, y: CSSUnitValue, z: CSSUnitValue, is2D: true}
console.log(transform[0].x); // CSSUnitValue {value: 0.95, unit: "number"}
console.log(transform[0].y); // CSSUnitValue {value: 0.95, unit: "number"}
console.log(transform[0].z); // CSSUnitValue {value: 1, unit: "number"}
console.log(transform.is2D); // true
// CSSImageValue
let bgImage = allComputedStyles.get("background-image");
console.log(bgImage); // CSSImageValue
console.log(bgImage.toString()); // url("magicwand.png")
// CSSUnparsedValue
let unit = allComputedStyles.get("--unit");
console.log(unit);
let parsedUnit = CSSNumericValue.parse(unit);
console.log(parsedUnit);
console.log(parsedUnit.unit);
console.log(parsedUnit.value);
```
We grab our `StylePropertyMapReadOnly` with the following JavaScript:
```js
const allComputedStyles = document.querySelector("button").computedStyleMap();
```
The following examples reference `allComputedStyles`:
### CSSUnparsedValue
The {{domxref('CSSUnparsedValue')}} represents [custom properties](/en-US/docs/Web/CSS/Using_CSS_custom_properties):
```js
// CSSUnparsedValue
const unit = allComputedStyles.get("--unit");
console.log(unit); // CSSUnparsedValue {0: " 1.2rem", length: 1}
console.log(unit[0]); // " 1.2rem"
```
When we invoke `get()`, a custom property of type `CSSUnparsedValue` is returned. Note the space before the `1.2rem`. To get a unit and value, we need a `CSSUnitValue`, which we can retrieve using the `CSSStyleValue.parse()` method on the `CSSUnparsedValue`.
```js
const parsedUnit = CSSNumericValue.parse(unit);
console.log(parsedUnit); // CSSUnitValue {value: 1.2, unit: "rem"}
console.log(parsedUnit.unit); // "rem"
console.log(parsedUnit.value); // 1.2
```
### CSSMathSum
Although the [`<button>`](/en-US/docs/Web/HTML/Element/button) element is an inline element by default, we've added [`display: inline-block;`](/en-US/docs/Web/CSS/CSS_display) to enable sizing. In our CSS we have `width: calc(30% + 20px);`, which is a [`calc()`](/en-US/docs/Web/CSS/calc) function to define the width.
When we `get()` the `width`, we get a [`CSSMathSum`](/en-US/docs/Web/API/CSSMathSum) returned. {{domxref('CSSMathSum.values')}} is a {{domxref('CSSNumericArray')}} with 2 `CSSUnitValues`.
The value of {{domxref('CSSMathValue.operator')}} is `sum`:
```js
const btnWidth = allComputedStyles.get("width");
console.log(btnWidth); // CSSMathSum
console.log(btnWidth.values); // CSSNumericArray {0: CSSUnitValue, 1: CSSUnitValue, length: 2}
console.log(btnWidth.operator); // 'sum'
```
### CSSTransformValue with CSSScale
The [`display: inline-block;`](/en-US/docs/Web/CSS/CSS_display) also enables transforming. In our CSS we have `transform: scale(0.95);`, which is a {{cssxref('transform')}} function.
```js
const transform = allComputedStyles.get("transform");
console.log(transform); // CSSTransformValue {0: CSSScale, 1: CSSTranslate, length: 2, is2D: true}
console.log(transform.length); // 1
console.log(transform[0]); // CSSScale {x: CSSUnitValue, y: CSSUnitValue, z: CSSUnitValue, is2D: true}
console.log(transform[0].x); // CSSUnitValue {value: 0.95, unit: "number"}
console.log(transform[0].y); // CSSUnitValue {value: 0.95, unit: "number"}
console.log(transform[0].z); // CSSUnitValue {value: 1, unit: "number"}
console.log(transform.is2D); // true
```
When we `get()` the `transform` property, we get a {{domxref('CSSTransformValue')}}. We can query the length (or number) of transform functions with the `length` property.
Seen as we have a length of `1`, which represents a single transform function, we log the first object and get a `CSSScale` object. We get `CSSUnitValues` when we query the `x`, `y`, and `z` scaling. The readonly `CSSScale.is2D` property is `true` in this scenario.
Had we added `translate()`, `skew()`, and `rotate()` transform functions, the length would have been `4`, each with their own `x`, `y`, `z` values, and each with an `.is2D` property. For example, had we included `transform: translate3d(1px, 1px, 3px)`, the `.get('transform')` would have returned a `CSSTranslate` with `CSSUnitValues` for `x`, `y`, and `z`, and the readonly `.is2D` property would have been `false`.
### CSSImageValue
Our button has one background image: a magic wand.
```js
const bgImage = allComputedStyles.get("background-image");
console.log(bgImage); // CSSImageValue
console.log(bgImage.toString()); // url("magicwand.png")
```
When we `get()` the `'background-image'`, a {{domxref('CSSImageValue')}} is returned. While we used the CSS {{cssxref('background')}} shorthand property, the inherited {{jsxref("Object/toString", "Object.prototype.toString()")}} method, shows we returned only the image, `'url("magicwand.png")'`.
Notice that the value returned is the absolute path to the image — this is returned even if the original `url()` value was relative. Had the background image been a gradient or multiple background images, `.get('background-image')` would have returned a `CSSStyleValue`. The `CSSImageValue` is returned only if there is a single image, and only if that single image declaration is a URL.
### Summary
This should get you started with understanding the CSS Typed OM. Take a look at all the [CSS Typed OM](/en-US/docs/Web/API/CSS_Typed_OM_API) interfaces to learn more.
## See also
- [Using the CSS Painting API](/en-US/docs/Web/API/CSS_Painting_API/Guide)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svganimatedenumeration/index.md | ---
title: SVGAnimatedEnumeration
slug: Web/API/SVGAnimatedEnumeration
page-type: web-api-interface
browser-compat: api.SVGAnimatedEnumeration
---
{{APIRef("SVG")}}
The **`SVGAnimatedEnumeration`** interface describes attribute values which are constants from a particular enumeration and which can be animated.
## Instance properties
- {{domxref("SVGAnimatedEnumeration.baseVal", "baseVal")}}
- : An integer that is the base value of the given attribute before applying any animations.
- {{domxref("SVGAnimatedEnumeration.animVal", "animVal")}}
- : If the given attribute or property is being animated, it contains the current animated value of the attribute or property. If the given attribute or property is not currently being animated, it contains the same value as `baseVal`.
## Instance methods
The `SVGAnimatedEnumeration` interface do not provide any specific methods.
## Examples
Considering this snippet with a {{SVGElement("clipPath")}} element: Its {{SVGAttr("clipPathUnits")}} is associated with a `SVGAnimatedEnumeration` object.
```html
<svg viewBox="0 0 100 100" width="200" height="200">
<clipPath id="clip1" clipPathUnits="userSpaceOnUse">
<circle cx="50" cy="50" r="35" />
</clipPath>
<!-- Some reference rect to materialized to clip path -->
<rect id="r1" x="0" y="0" width="45" height="45" />
</svg>
```
This snippet gets the element, and logs the `baseVal` and `animVal`of the {{domxref("SVGClipPathElement.clipPathUnits")}} property. As no animation is happening, they have the same value.
```js
const clipPathElt = document.getElementById("clip1");
console.log(clipPathElt.clipPathUnits.baseVal); // Logs 1 that correspond to userSpaceOnUse
console.log(clipPathElt.clipPathUnits.animVal); // Logs 1 that correspond to userSpaceOnUse
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/svganimatedenumeration | data/mdn-content/files/en-us/web/api/svganimatedenumeration/baseval/index.md | ---
title: "SVGAnimatedEnumeration: baseVal property"
short-title: baseVal
slug: Web/API/SVGAnimatedEnumeration/baseVal
page-type: web-api-instance-property
browser-compat: api.SVGAnimatedEnumeration.baseVal
---
{{APIRef("SVG")}}
The **`baseVal`** property of the {{domxref("SVGAnimatedEnumeration")}} interface contains the initial value of an SVG enumeration.
## Value
An integer containing the initial value of the enumeration
## Examples
Considering this snippet with a {{SVGElement("clipPath")}} element: Its {{SVGAttr("clipPathUnits")}} is associated with a {{domxref("SVGAnimatedEnumeration")}} object.
```html
<svg viewBox="0 0 100 100" width="200" height="200">
<clipPath id="clip1" clipPathUnits="userSpaceOnUse">
<circle cx="50" cy="50" r="35" />
</clipPath>
<!-- Some reference rect to materialized to clip path -->
<rect id="r1" x="0" y="0" width="45" height="45" />
</svg>
```
This snippet gets the element, and logs the `baseVal`of the {{domxref("SVGClipPathElement.clipPathUnits")}} property.
```js
const clipPathElt = document.getElementById("clip1");
console.log(clipPathElt.clipPathUnits.baseVal); // Logs 1 that correspond to userSpaceOnUse
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("SVGAnimatedEnumeration.animVal")}}
| 0 |
data/mdn-content/files/en-us/web/api/svganimatedenumeration | data/mdn-content/files/en-us/web/api/svganimatedenumeration/animval/index.md | ---
title: "SVGAnimatedEnumeration: animVal property"
short-title: animVal
slug: Web/API/SVGAnimatedEnumeration/animVal
page-type: web-api-instance-property
browser-compat: api.SVGAnimatedEnumeration.animVal
---
{{APIRef("SVG")}}
The **`animVal`** property of the {{domxref("SVGAnimatedEnumeration")}} interface contains the current value of an SVG enumeration. If there is no animation, it is the same value as the {{domxref("SVGAnimatedEnumeration.baseVal", "baseVal")}}.
## Value
An integer containing the current value of the enumeration
## Examples
```css hidden
html,
body,
svg {
height: 100%;
}
```
```html
<div>
<svg viewBox="0 0 100 100" width="200" height="200">
<clipPath id="clip1" clipPathUnits="userSpaceOnUse">
<animate
attributeName="clipPathUnits"
values="userSpaceOnUse;objectBoundingBox;userSpaceOnUse"
dur="2s"
repeatCount="indefinite" />
<circle cx="50" cy="50" r="25" />
</clipPath>
<rect id="r1" x="0" y="0" width="50" height="100" />
<use clip-path="url(#clip1)" href="#r1" fill="lightblue" />
</svg>
</div>
<pre id="log"></pre>
```
```js
const clipPath1 = document.getElementById("clip1");
const log = document.getElementById("log");
function displayLog() {
const animValue = clipPath1.clipPathUnits.animVal;
const baseValue = clipPath1.clipPathUnits.baseVal;
log.textContent = `The 'clipPathUnits.animVal' is ${animValue}.\n`;
log.textContent += `The 'clipPathUnits.baseVal' is ${baseValue}.`;
requestAnimationFrame(displayLog);
}
displayLog();
```
{{EmbedLiveSample("Examples", "280", "260")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("SVGAnimatedEnumeration.baseVal")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/windowcontrolsoverlaygeometrychangeevent/index.md | ---
title: WindowControlsOverlayGeometryChangeEvent
slug: Web/API/WindowControlsOverlayGeometryChangeEvent
page-type: web-api-interface
status:
- experimental
browser-compat: api.WindowControlsOverlayGeometryChangeEvent
---
{{APIRef("Window Controls Overlay API")}}{{SeeCompatTable}}
The **`WindowControlsOverlayGeometryChangeEvent`** interface of the [Window Controls Overlay API](/en-US/docs/Web/API/Window_Controls_Overlay_API) is passed to {{domxref("WindowControlsOverlay/geometrychange_event", "geometrychange")}} when the size or visibility of a desktop Progress Web App's title bar region changes.
{{InheritanceDiagram}}
## Constructor
- {{domxref("WindowControlsOverlayGeometryChangeEvent.WindowControlsOverlayGeometryChangeEvent", "WindowControlsOverlayGeometryChangeEvent()")}} {{Experimental_Inline}}
- : Creates a `WindowControlsOverlayGeometryChangeEvent` event with the given parameters.
## Instance properties
_Also inherits properties from its parent {{domxref("Event")}}_.
- {{domxref("WindowControlsOverlayGeometryChangeEvent.titlebarAreaRect")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A {{domxref("DOMRect")}} representing the position and size of the title bar region.
- {{domxref("WindowControlsOverlayGeometryChangeEvent.visible")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : A {{Glossary("Boolean")}} that indicates whether the window controls overlay is visible or not.
## Examples
The following example shows how to use a `WindowControlsOverlayGeometryChangeEvent` instance by adding an
event handler on the {{domxref("Navigator.windowControlsOverlay")}} property, to listen to geometry changes of a PWA's title bar region.
```js
if ("windowControlsOverlay" in navigator) {
navigator.windowControlsOverlay.addEventListener(
"geometrychange",
(event) => {
if (event.visible) {
const rect = event.titlebarAreaRect;
// Do something with the coordinates of the title bar area.
}
},
);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [Window Controls Overlay API](/en-US/docs/Web/API/Window_Controls_Overlay_API).
| 0 |
data/mdn-content/files/en-us/web/api/windowcontrolsoverlaygeometrychangeevent | data/mdn-content/files/en-us/web/api/windowcontrolsoverlaygeometrychangeevent/visible/index.md | ---
title: "WindowControlsOverlayGeometryChangeEvent: visible property"
short-title: visible
slug: Web/API/WindowControlsOverlayGeometryChangeEvent/visible
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.WindowControlsOverlayGeometryChangeEvent.visible
---
{{APIRef("Window Controls Overlay API")}}{{SeeCompatTable}}
The **`visible`** read-only property of the {{domxref("WindowControlsOverlayGeometryChangeEvent")}} interface is a boolean flag that indicates whether the window controls overlay is visible or not in a desktop-installed Progressive Web App.
If the user opts-out of the [Window Controls Overlay](/en-US/docs/Web/API/Window_Controls_Overlay_API) feature, the default title bar appears and the window controls buttons do not appear as an overlay, in which case the `visible` flag is false.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/windowcontrolsoverlaygeometrychangeevent | data/mdn-content/files/en-us/web/api/windowcontrolsoverlaygeometrychangeevent/titlebararearect/index.md | ---
title: "WindowControlsOverlayGeometryChangeEvent: titlebarAreaRect property"
short-title: titlebarAreaRect
slug: Web/API/WindowControlsOverlayGeometryChangeEvent/titlebarAreaRect
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.WindowControlsOverlayGeometryChangeEvent.titlebarAreaRect
---
{{APIRef("Window Controls Overlay API")}}{{SeeCompatTable}}
The **`titlebarAreaRect`** read-only property of the {{domxref("WindowControlsOverlayGeometryChangeEvent")}} interface is a {{domxref("DOMRect")}} representing the position and size of the area occupied by the title bar in a desktop-installed Progressive Web App.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/windowcontrolsoverlaygeometrychangeevent | data/mdn-content/files/en-us/web/api/windowcontrolsoverlaygeometrychangeevent/windowcontrolsoverlaygeometrychangeevent/index.md | ---
title: "WindowControlsOverlayGeometryChangeEvent: WindowControlsOverlayGeometryChangeEvent() constructor"
short-title: WindowControlsOverlayGeometryChangeEvent()
slug: Web/API/WindowControlsOverlayGeometryChangeEvent/WindowControlsOverlayGeometryChangeEvent
page-type: web-api-constructor
status:
- experimental
browser-compat: api.WindowControlsOverlayGeometryChangeEvent.WindowControlsOverlayGeometryChangeEvent
---
{{APIRef("Window Controls Overlay API")}}{{SeeCompatTable}}
The **`WindowControlsOverlayGeometryChangeEvent()`** constructor returns a new {{domxref("WindowControlsOverlayGeometryChangeEvent")}} object, representing the current geometry of a desktop Progressive Web App's title bar area.
## Syntax
```js-nolint
new WindowControlsOverlayGeometryChangeEvent(type, options)
```
### Parameters
_The `WindowControlsOverlayGeometryChangeEvent()` constructor also inherits arguments from
{{domxref("Event.Event", "Event()")}}._
- `type`
- : A string indicating the event type. It is case-sensitive and browsers set it to `geometrychange`.
- `options`
- : An object with the following properties:
- `visible` {{optional_inline}}
- : A boolean flag that's true when the `titlebarAreaRect` object's values are not 0. Its default value is `false`.
- `titlebarAreaRect`
- : A {{domxref("DOMRect")}} representing the position and size of the title bar area.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("WindowControlsOverlayGeometryChangeEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/speechgrammarlist/index.md | ---
title: SpeechGrammarList
slug: Web/API/SpeechGrammarList
page-type: web-api-interface
status:
- experimental
browser-compat: api.SpeechGrammarList
---
{{APIRef("Web Speech API")}}{{SeeCompatTable}}
The **`SpeechGrammarList`** interface of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) represents a list of {{domxref("SpeechGrammar")}} objects containing words or patterns of words that we want the recognition service to recognize.
Grammar is defined using [JSpeech Grammar Format](https://www.w3.org/TR/jsgf/) (**JSGF**.) Other formats may also be supported in the future.
## Constructor
- {{domxref("SpeechGrammarList.SpeechGrammarList", "SpeechGrammarList()")}} {{Experimental_Inline}}
- : Creates a new `SpeechGrammarList` object.
## Instance properties
- {{domxref("SpeechGrammarList.length")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the number of {{domxref("SpeechGrammar")}} objects contained in the `SpeechGrammarList`.
## Instance methods
- {{domxref("SpeechGrammarList.item()")}} {{Experimental_Inline}}
- : Standard getter — allows individual {{domxref("SpeechGrammar")}} objects to be retrieved from the `SpeechGrammarList` using array syntax.
- {{domxref("SpeechGrammarList.addFromURI()")}} {{Experimental_Inline}}
- : Takes a grammar present at a specific URI and adds it to the `SpeechGrammarList` as a new {{domxref("SpeechGrammar")}} object.
- {{domxref("SpeechGrammarList.addFromString()")}} {{Experimental_Inline}}
- : Adds a grammar in a string to the `SpeechGrammarList` as a new {{domxref("SpeechGrammar")}} object.
## Examples
In our simple [Speech color changer](https://github.com/mdn/dom-examples/tree/main/web-speech-api/speech-color-changer) example, we create a new `SpeechRecognition` object instance using the {{domxref("SpeechRecognition.SpeechRecognition", "SpeechRecognition()")}} constructor, create a new {{domxref("SpeechGrammarList")}}, add our grammar string to it using the {{domxref("SpeechGrammarList.addFromString")}} method, and set it to be the grammar that will be recognized by the `SpeechRecognition` instance using the {{domxref("SpeechRecognition.grammars")}} property.
```js
const grammar =
"#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
| 0 |
data/mdn-content/files/en-us/web/api/speechgrammarlist | data/mdn-content/files/en-us/web/api/speechgrammarlist/length/index.md | ---
title: "SpeechGrammarList: length property"
short-title: length
slug: Web/API/SpeechGrammarList/length
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.SpeechGrammarList.length
---
{{APIRef("Web Speech API")}}{{ SeeCompatTable() }}
The **`length`** read-only property of the
{{domxref("SpeechGrammarList")}} interface returns the number of
{{domxref("SpeechGrammar")}} objects contained in the {{domxref("SpeechGrammarList")}}.
## Value
A number indicating the number of {{domxref("SpeechGrammar")}} objects contained in the
{{domxref("SpeechGrammarList")}}.
## Examples
```js
const grammar =
"#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
speechRecognitionList.length; // should return 1.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
| 0 |
data/mdn-content/files/en-us/web/api/speechgrammarlist | data/mdn-content/files/en-us/web/api/speechgrammarlist/item/index.md | ---
title: "SpeechGrammarList: item() method"
short-title: item()
slug: Web/API/SpeechGrammarList/item
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SpeechGrammarList.item
---
{{APIRef("Web Speech API")}}{{ SeeCompatTable() }}
The **`item`** getter of the {{domxref("SpeechGrammarList")}}
interface is a standard getter — it allows individual {{domxref("SpeechGrammar")}}
objects to be retrieved from the `SpeechGrammarList` using array syntax.
## Syntax
```js-nolint
item(index)
```
### Parameters
- `index`
- : Index of the item to retrieve.
### Return value
A {{domxref("SpeechGrammar")}} object.
## Examples
```js
const grammar =
"#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
const myFirstGrammar = speechRecognitionList[0]; // variable contain the object created above
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
| 0 |
data/mdn-content/files/en-us/web/api/speechgrammarlist | data/mdn-content/files/en-us/web/api/speechgrammarlist/addfromstring/index.md | ---
title: "SpeechGrammarList: addFromString() method"
short-title: addFromString()
slug: Web/API/SpeechGrammarList/addFromString
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SpeechGrammarList.addFromString
---
{{APIRef("Web Speech API")}}{{ SeeCompatTable() }}
The **`addFromString()`** method of the
{{domxref("SpeechGrammarList")}} interface takes a grammar present in a specific
string within the code base (e.g. stored in a variable) and adds it to
the `SpeechGrammarList` as a new {{domxref("SpeechGrammar")}} object.
## Syntax
```js-nolint
addFromString(string)
addFromString(string, weight)
```
### Parameters
- `string`
- : A string representing the grammar to be added.
- `weight` {{optional_inline}}
- : A float representing the weight of the grammar relative to other grammars present in
the {{domxref("SpeechGrammarList")}}. The weight means the importance of this grammar,
or the likelihood that it will be recognized by the speech recognition service. The
value can be between `0.0` and `1.0`; If not specified, the
default used is `1.0`.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
const grammar =
"#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
| 0 |
data/mdn-content/files/en-us/web/api/speechgrammarlist | data/mdn-content/files/en-us/web/api/speechgrammarlist/speechgrammarlist/index.md | ---
title: "SpeechGrammarList: SpeechGrammarList() constructor"
short-title: SpeechGrammarList()
slug: Web/API/SpeechGrammarList/SpeechGrammarList
page-type: web-api-constructor
status:
- experimental
browser-compat: api.SpeechGrammarList.SpeechGrammarList
---
{{APIRef("Web Speech API")}}{{ SeeCompatTable() }}
The **`SpeechGrammarList()`** constructor creates a new
`SpeechGrammarList` object instance.
## Syntax
```js-nolint
new SpeechGrammarList()
```
### Parameters
None.
## Examples
In our simple [Speech color changer](https://github.com/mdn/dom-examples/tree/main/web-speech-api/speech-color-changer) example, we create a new `SpeechRecognition` object
instance using the {{domxref("SpeechRecognition.SpeechRecognition",
"SpeechRecognition()")}} constructor, create a new {{domxref("SpeechGrammarList")}}, add
our grammar string to it using the {{domxref("SpeechGrammarList.addFromString")}}
method, and set it to be the grammar that will be recognized by the
`SpeechRecognition` instance using the
{{domxref("SpeechRecognition.grammars")}} property.
```js
const grammar =
"#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
| 0 |
data/mdn-content/files/en-us/web/api/speechgrammarlist | data/mdn-content/files/en-us/web/api/speechgrammarlist/addfromuri/index.md | ---
title: "SpeechGrammarList: addFromURI() method"
short-title: addFromURI()
slug: Web/API/SpeechGrammarList/addFromURI
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.SpeechGrammarList.addFromURI
---
{{APIRef("Web Speech API")}}{{ SeeCompatTable() }}
The **`addFromURI()`** method of the
{{domxref("SpeechGrammarList")}} interface takes a grammar present at a specific URI and
adds it to the `SpeechGrammarList` as a new {{domxref("SpeechGrammar")}}
object.
Note that some speech recognition services may support built-in grammars that can be
specified by URI.
## Syntax
```js-nolint
addFromURI(src)
addFromURI(src, weight)
```
### Parameters
- `src`
- : A string representing the URI of the grammar to be added.
- `weight` {{optional_inline}}
- : A float representing the weight of the grammar relative to other grammars present in
the {{domxref("SpeechGrammarList")}}. The weight means the importance of this grammar,
or the likelihood that it will be recognized by the speech recognition service. The
value can be between `0.0` and `1.0`; If not specified, the
default used is `1.0`.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
const grammar =
"#JSGF V1.0; grammar colors; public <color> = aqua | azure | beige | bisque | black | blue | brown | chocolate | coral | crimson | cyan | fuchsia | ghostwhite | gold | goldenrod | gray | green | indigo | ivory | khaki | lavender | lime | linen | magenta | maroon | moccasin | navy | olive | orange | orchid | peru | pink | plum | purple | red | salmon | sienna | silver | snow | tan | teal | thistle | tomato | turquoise | violet | white | yellow ;";
const recognition = new SpeechRecognition();
const speechRecognitionList = new SpeechGrammarList();
speechRecognitionList.addFromString(grammar, 1);
recognition.grammars = speechRecognitionList;
speechRecognitionList.addFromURI("http://www.example.com/grammar.txt"); // adds a second grammar to the list.
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/backgroundfetchrecord/index.md | ---
title: BackgroundFetchRecord
slug: Web/API/BackgroundFetchRecord
page-type: web-api-interface
status:
- experimental
browser-compat: api.BackgroundFetchRecord
---
{{APIRef("Background Fetch API")}}{{SeeCompatTable}}
The **`BackgroundFetchRecord`** interface of the {{domxref('Background Fetch API','','',' ')}} represents an individual request and response.
A `BackgroundFetchRecord` is created by the {{domxref("BackgroundFetchRegistration.match()","BackgroundFetchRegistration.matchAll()")}} method, therefore there is no constructor for this interface.
There will be one `BackgroundFetchRecord` for each resource requested by `fetch()`.
## Instance properties
- {{domxref("BackgroundFetchRecord.request","request")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{domxref("Request")}}.
- {{domxref("BackgroundFetchRecord.responseReady","responseReady")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a promise that resolves with a {{domxref("Response")}}.
## Examples
In this example an individual `BackgroundFetchRecord` is returned using {{domxref("BackgroundFetchRegistration.match()","BackgroundFetchRegistration.matchAll()")}}. The {{domxref("BackgroundFetchRecord.request")}} and {{domxref("BackgroundFetchRecord.responseReady")}} are returned and logged to the console.
```js
bgFetch.match("/ep-5.mp3").then(async (record) => {
if (!record) {
console.log("No record found");
return;
}
console.log(`Here's the request`, record.request);
const response = await record.responseReady;
console.log(`And here's the response`, response);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/backgroundfetchrecord | data/mdn-content/files/en-us/web/api/backgroundfetchrecord/request/index.md | ---
title: "BackgroundFetchRecord: request property"
short-title: request
slug: Web/API/BackgroundFetchRecord/request
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BackgroundFetchRecord.request
---
{{APIRef("Background Fetch API")}}{{SeeCompatTable}}
The **`request`** read-only property of the {{domxref("BackgroundFetchRecord")}} interface returns the details of the resource to be fetched.
## Value
A {{domxref("Request")}}.
## Examples
In this example an individual `BackgroundFetchRecord` is returned using {{domxref("BackgroundFetchManager.fetch()","BackgroundFetchManager.fetch()")}}. The `request` is returned and logged to the console.
```js
bgFetch.match("/ep-5.mp3").then(async (record) => {
if (!record) {
console.log("No record found");
return;
}
console.log(`Here's the request`, record.request);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/backgroundfetchrecord | data/mdn-content/files/en-us/web/api/backgroundfetchrecord/responseready/index.md | ---
title: "BackgroundFetchRecord: responseReady property"
short-title: responseReady
slug: Web/API/BackgroundFetchRecord/responseReady
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.BackgroundFetchRecord.responseReady
---
{{APIRef("Background Fetch API")}}{{SeeCompatTable}}
The **`responseReady`** read-only property of the {{domxref("BackgroundFetchRecord")}} interface returns a {{jsxref("Promise")}} that resolves with a {{domxref("Response")}}.
## Value
A {{jsxref("Promise")}} that resolves with a {{domxref("Response")}}.
## Examples
In this example an individual `BackgroundFetchRecord` is returned using {{domxref("BackgroundFetchManager.fetch()","BackgroundFetchManager.fetch()")}}. The value of `responseReady` is returned and logged to the console.
```js
bgFetch.match("/ep-5.mp3").then(async (record) => {
if (!record) {
console.log("No record found");
return;
}
const response = await record.responseReady;
console.log(`Here's the response`, response);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmllinkelement/index.md | ---
title: HTMLLinkElement
slug: Web/API/HTMLLinkElement
page-type: web-api-interface
browser-compat: api.HTMLLinkElement
---
{{ APIRef("HTML DOM") }}
The **`HTMLLinkElement`** interface represents reference information for external resources and the relationship of those resources to a document and vice versa (corresponds to [`<link>`](/en-US/docs/Web/HTML/Element/link) element; not to be confused with [`<a>`](/en-US/docs/Web/HTML/Element/a), which is represented by [`HTMLAnchorElement`](/en-US/docs/Web/API/HTMLAnchorElement)). This object inherits all of the properties and methods of the {{domxref("HTMLElement")}} interface.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLLinkElement.as")}}
- : A string representing the type of content being loaded by the HTML link when [`rel="preload"`](/en-US/docs/Web/HTML/Attributes/rel/preload) or [`rel="modulepreload"`](/en-US/docs/Web/HTML/Attributes/rel/modulepreload).
- {{domxref("HTMLLinkElement.crossOrigin")}}
- : A string that corresponds to the CORS setting for this link element. See [CORS settings attributes](/en-US/docs/Web/HTML/Attributes/crossorigin) for details.
- {{domxref("HTMLLinkElement.disabled")}}
- : A boolean value which represents whether the link is disabled; currently only used with style sheet links.
- {{domxref("HTMLLinkElement.fetchPriority")}}
- : An optional string representing a hint given to the browser on how it should prioritize fetching of a preload relative to other resources of the same type. If this value is provided, it must be one of the possible permitted values: `high` to fetch at a higher priority, `low` to fetch at a lower priority, or `auto` to indicate no preference (which is the default).
- {{domxref("HTMLLinkElement.href")}}
- : A string representing the URI for the target resource.
- {{domxref("HTMLLinkElement.hreflang")}}
- : A string representing the language code for the linked resource.
- {{domxref("HTMLLinkElement.media")}}
- : A string representing a list of one or more media formats to which the resource applies.
- {{domxref("HTMLLinkElement.referrerPolicy")}}
- : A string that reflects the [`referrerpolicy`](/en-US/docs/Web/HTML/Element/link#referrerpolicy) HTML attribute indicating which referrer to use.
- {{domxref("HTMLLinkElement.rel")}}
- : A string representing the forward relationship of the linked resource from the document to the resource.
- {{domxref("HTMLLinkElement.relList")}} {{ReadOnlyInline}}
- : A {{domxref("DOMTokenList")}} that reflects the [`rel`](/en-US/docs/Web/HTML/Element/link#rel) HTML attribute, as a list of tokens.
- {{domxref("HTMLLinkElement.sizes")}} {{ReadOnlyInline}}
- : A {{domxref("DOMTokenList")}} that reflects the [`sizes`](/en-US/docs/Web/HTML/Element/link#sizes) HTML attribute, as a list of tokens.
- {{domxref("HTMLLinkElement.sheet")}} {{ReadOnlyInline}}
- : Returns the {{domxref("StyleSheet")}} object associated with the given element, or `null` if there is none.
- {{domxref("HTMLLinkElement.type")}}
- : A string representing the MIME type of the linked resource.
### Obsolete properties
- {{domxref("HTMLLinkElement.charset")}} {{deprecated_inline}}
- : A string representing the character encoding for the target resource.
- {{domxref("HTMLLinkElement.rev")}} {{deprecated_inline}}
- : A string representing the reverse relationship of the linked resource from the resource to the document.
> **Note:** Currently the W3C HTML 5.2 spec states that `rev` is no longer obsolete, whereas the WHATWG living standard still has it labeled obsolete. Until this discrepancy is resolved, you should still assume it is obsolete.
- {{domxref("HTMLLinkElement.target")}} {{deprecated_inline}}
- : A string representing the name of the target frame to which the resource applies.
## Instance methods
_No specific method; inherits methods from its parent, {{domxref("HTMLElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{HTMLElement("link")}}.
| 0 |
data/mdn-content/files/en-us/web/api/htmllinkelement | data/mdn-content/files/en-us/web/api/htmllinkelement/fetchpriority/index.md | ---
title: "HTMLLinkElement: fetchPriority property"
short-title: fetchPriority
slug: Web/API/HTMLLinkElement/fetchPriority
page-type: web-api-instance-property
browser-compat: api.HTMLLinkElement.fetchPriority
---
{{APIRef("HTML DOM")}}
The **`fetchPriority`** property of the
{{domxref("HTMLLinkElement")}} interface represents a hint given to the browser
on how it should prioritize the preload of the given resource relative to other
resources of the same type.
## Value
A string representing the priority hint. Possible values are:
- `high`
- : Fetch the preload at a high priority relative to other resources
of the same type.
- `low`
- : Fetch the image at a low priority relative to other resources of
the same type.
- `auto`
- : Default mode, which indicates no preference for
the fetch priority. The browser decides what is best for the user.
The `fetchPriority` property allows you to signal high or low priority preload
fetches. This can be useful when applied to {{HTMLElement("link")}} elements
to signal preloads that are more or less important to the user experience early
in the loading process.
The effects of the hint on resource loading is browser-specific so make sure to
test on multiple browser engines.
Use it sparingly for exceptional cases where the browser may not be able to
infer the best way to load the resource automatically. Over use can result in
degrading performance.
## Examples
```js
const preloadLink = document.createElement("link");
preloadLink.href = "myimage.jpg";
preloadLink.rel = "preload";
preloadLink.as = "image";
preloadLink.fetchPriority = "high";
document.head.appendChild(preloadLink);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmllinkelement | data/mdn-content/files/en-us/web/api/htmllinkelement/crossorigin/index.md | ---
title: "HTMLLinkElement: crossOrigin property"
short-title: crossOrigin
slug: Web/API/HTMLLinkElement/crossOrigin
page-type: web-api-instance-property
browser-compat: api.HTMLLinkElement.crossOrigin
---
{{APIRef("HTML DOM")}}
The **`crossOrigin`** property of the {{domxref("HTMLLinkElement")}} interface specifies the Cross-Origin Resource Sharing ({{Glossary("CORS")}}) setting to use when retrieving the resource.
## Value
A string of a keyword specifying the CORS mode to use when fetching the resource. Possible values are:
- `anonymous` or the empty string (`""`)
- : Requests sent by the {{domxref("HTMLLinkElement")}} will use the `cors` {{domxref("Request.mode", "mode", "", "nocode")}} and the `same-origin` {{domxref("Request.credentials", "credentials", "", "nocode")}} mode. This means that CORS is enabled and credentials are sent _if_ the resource is fetched from the same origin from which the document was loaded.
- `use-credentials`
- : Requests sent by the {{domxref("HTMLLinkElement")}} will use the `cors` {{domxref("Request.mode", "mode", "", "nocode")}} and the `include` {{domxref("Request.credentials", "credentials", "", "nocode")}} mode. All resources requests by the element will use CORS, regardless of what domain the fetch is from.
If the `crossOrigin` property is specified with any other value, it is the same as specifing as the `anonymous`.
If the `crossOrigin` property is not specified, the resource is fetched without CORS (the `no-cors` {{domxref("Request.mode", "mode", "", "nocode")}} and the `same-origin` {{domxref("Request.credentials", "credentials", "", "nocode")}} mode).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLImageElement.crossOrigin")}}
- {{domxref("HTMLMediaElement.crossOrigin")}}
- {{domxref("HTMLScriptElement.crossOrigin")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmllinkelement | data/mdn-content/files/en-us/web/api/htmllinkelement/as/index.md | ---
title: "HTMLLinkElement: as property"
short-title: as
slug: Web/API/HTMLLinkElement/as
page-type: web-api-instance-property
browser-compat: api.HTMLLinkElement.as
---
{{APIRef("HTML DOM")}}
The **`as`** property of the {{domxref("HTMLLinkElement")}} interface returns a string representing the type of content to be preloaded by a link element.
The `as` property must have a value for link elements when [`rel="preload"`](/en-US/docs/Web/HTML/Attributes/rel/preload), or the resource will not be fetched.
It may also be applied to link elements where [`rel="modulepreload"`](/en-US/docs/Web/HTML/Attributes/rel/preload), but if omitted, will default to `script`.
The property should not be set for other types of link elements, such as `rel="prefetch"`.
This property reflects the value of the [`as` attribute](/en-US/docs/Web/HTML/Element/link#as) of the [`<link>`](/en-US/docs/Web/HTML/Element/link) HTML element.
## Value
A string with the following allowed values: `"audio"`, `"document"`, `"embed"`, `"fetch"`, `"font"`, `"image"`, `"object"`, `"script"`, `"style"`, `"track"`, `"video"`, `"worker"`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmllinkelement | data/mdn-content/files/en-us/web/api/htmllinkelement/sheet/index.md | ---
title: "HTMLLinkElement: sheet property"
short-title: sheet
slug: Web/API/HTMLLinkElement/sheet
page-type: web-api-instance-property
browser-compat: api.HTMLLinkElement.sheet
---
{{APIRef("HTML DOM")}}
The read-only **`sheet`** property of the {{domxref("HTMLLinkElement")}} interface
contains the stylesheet associated with that element.
A stylesheet is associated to an `HTMLLinkElement` if `rel="stylesheet"` is used with `<link>`.
## Value
A {{DOMxRef("StyleSheet")}} object, or `null` if none is associated with the element.
## Examples
```html
<html>
<header>
<link rel="stylesheet" href="styles.css" />
…
</header>
</html>
```
The `sheet` property of the `HTMLLinkElement` object will return the {{domxref("StyleSheet")}} object describing `styles.css`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/htmllinkelement | data/mdn-content/files/en-us/web/api/htmllinkelement/rellist/index.md | ---
title: "HTMLLinkElement: relList property"
short-title: relList
slug: Web/API/HTMLLinkElement/relList
page-type: web-api-instance-property
browser-compat: api.HTMLLinkElement.relList
---
{{ APIRef("HTML DOM") }}
The **`HTMLLinkElement.relList`** read-only property reflects the [`rel`](/en-US/docs/Web/HTML/Attributes/rel) attribute. It is a live {{domxref("DOMTokenList")}} containing the set of link types indicating the relationship between the resource represented by the {{HTMLElement("link")}} element and the current document.
The property itself is read-only, meaning you can not substitute the
{{domxref("DOMTokenList")}} by another one, but the content of the returned list can be
changed.
## Value
A live {{domxref("DOMTokenList")}} of strings.
## Examples
```js
const links = document.getElementsByTagName("link");
for (const link of links) {
console.log("New link found.");
link.relList.forEach((relEntry) => {
console.log(relEntry);
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The equivalent property on {{HTMLElement("a")}} and {{HTMLElement("area")}},
{{domxref("HTMLAnchorElement.relList")}} and {{domxref("HTMLAreaElement.relList")}}.
- The very same list but as a space-separated tokens in a string:
{{domxref("HTMLLinkElement.rel")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmllinkelement | data/mdn-content/files/en-us/web/api/htmllinkelement/rel/index.md | ---
title: "HTMLLinkElement: rel property"
short-title: rel
slug: Web/API/HTMLLinkElement/rel
page-type: web-api-instance-property
browser-compat: api.HTMLLinkElement.rel
---
{{ APIRef("HTML DOM") }}
The **`HTMLLinkElement.rel`** property reflects the [`rel`](/en-US/docs/Web/HTML/Attributes/rel) attribute. It is a string containing a space-separated list of link types indicating the relationship between the resource represented by the {{HTMLElement("link")}} element and the current document.
The most common use of this attribute is to specify a link to an external style sheet:
the property is set to `stylesheet`, and the [`href`](/en-US/docs/Web/HTML/Element/link#href)
attribute is set to the URL of an external style sheet to format the page.
## Value
A string.
## Examples
```js
const links = document.getElementsByTagName("link");
for (const link of links) {
console.log(link);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The equivalent property on {{HTMLElement("a")}} and {{HTMLElement("area")}},
{{domxref("HTMLAnchorElement.rel")}} and {{domxref("HTMLAreaElement.rel")}}.
- The very same list but as tokens: {{domxref("HTMLLinkElement.relList")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmllinkelement | data/mdn-content/files/en-us/web/api/htmllinkelement/referrerpolicy/index.md | ---
title: "HTMLLinkElement: referrerPolicy property"
short-title: referrerPolicy
slug: Web/API/HTMLLinkElement/referrerPolicy
page-type: web-api-instance-property
browser-compat: api.HTMLLinkElement.referrerPolicy
---
{{APIRef}}
The
**`HTMLLinkElement.referrerPolicy`**
property reflects the HTML [`referrerpolicy`](/en-US/docs/Web/HTML/Element/link#referrerpolicy) attribute of the
{{HTMLElement("link")}} element defining which referrer is sent when fetching the
resource.
See the HTTP {{HTTPHeader("Referrer-Policy")}} header for details.
## Value
A string; one of the following:
- `no-referrer`
- : The {{HTTPHeader("Referer")}} header will be omitted entirely. No referrer
information is sent along with requests.
- `no-referrer-when-downgrade`
- : The URL is sent
as a referrer when the protocol security level stays the same (e.g.HTTP→HTTP,
HTTPS→HTTPS), but isn't sent to a less secure destination (e.g. HTTPS→HTTP).
- `origin`
- : Only send the origin of the document as the referrer in all cases.
The document `https://example.com/page.html` will send the referrer
`https://example.com/`.
- `origin-when-cross-origin`
- : Send a full URL when performing a same-origin request, but only send the origin of
the document for other cases.
- `same-origin`
- : A referrer will be sent for [same-site origins](/en-US/docs/Web/Security/Same-origin_policy), but
cross-origin requests will contain no referrer information.
- `strict-origin`
- : Only send the origin of the document as the referrer when the protocol security
level stays the same (e.g. HTTPS→HTTPS), but don't send it to a less secure
destination (e.g. HTTPS→HTTP).
- `strict-origin-when-cross-origin` (default)
- : This is the user agent's default behavior if no policy is specified. Send a full URL when performing a same-origin request, only send the origin when the
protocol security level stays the same (e.g. HTTPS→HTTPS), and send no header to a
less secure destination (e.g. HTTPS→HTTP).
- `unsafe-url`
- : Send a full URL when performing a same-origin or cross-origin request. This policy
will leak origins and paths from TLS-protected resources to insecure origins.
Carefully consider the impact of this setting.
## Examples
```js
const links = document.getElementsByTagName("link");
links[0].referrerPolicy; // "no-referrer"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- HTTP header {{HTTPHeader("Referrer-Policy")}}
- {{domxref("HTMLAnchorElement.referrerPolicy")}}
- {{domxref("HTMLAreaElement.referrerPolicy")}}
- {{domxref("HTMLIFrameElement.referrerPolicy")}}
- {{domxref("HTMLImageElement.referrerPolicy")}}
| 0 |
data/mdn-content/files/en-us/web/api/htmllinkelement | data/mdn-content/files/en-us/web/api/htmllinkelement/hreflang/index.md | ---
title: "HTMLLinkElement: hreflang property"
short-title: hreflang
slug: Web/API/HTMLLinkElement/hreflang
page-type: web-api-instance-property
browser-compat: api.HTMLLinkElement.hreflang
---
{{ApiRef("HTML DOM")}}
The **`hreflang`** property of the {{domxref("HTMLLinkElement")}} is used to indicate the language and the geographical targeting of a page. This hint can be used by browsers to select the more appropriate page or to improve {{Glossary("SEO")}}.
It reflects the `hreflang` attribute of the {{HTMLElement("link")}} element and is the empty string (`""`) if there is no `hreflang` attribute.
## Value
A string that contains a language tag, or the empty string (`""`) if there is no `hreflang` attribute.
## Example
```html
<link
rel="alternate"
href="www.example.com/fr/html"
hreflang="fr"
type="text/html"
title="French HTML" />
<p class="tag"></p>
```
```css
.tag {
margin-left: 20px;
font: bold;
font-size: 24px;
}
```
```js
const myLink = document.querySelector("link");
const pTag = document.querySelector(".tag");
pTag.textContent = myLink.hreflang;
```
## Results
{{EmbedLiveSample("Example",100,100)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("HTMLAnchorElement.hreflang")}} property
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/installevent/index.md | ---
title: InstallEvent
slug: Web/API/InstallEvent
page-type: web-api-interface
status:
- deprecated
- non-standard
browser-compat: api.InstallEvent
---
{{APIRef("Service Workers API")}}{{Deprecated_Header}}{{Non-standard_Header}}
> **Note:** Instead of using the deprecated `ServiceWorkerGlobalScope.oninstall` handler to catch events of this type, handle the (non-deprecated) {{domxref("ServiceWorkerGlobalScope/install_event", "install")}} event using a listener added with {{domxref("EventTarget/addEventListener", "addEventListener")}}.
The parameter passed into the {{domxref("ServiceWorkerGlobalScope.install_event", "oninstall")}} handler, the `InstallEvent` interface represents an install action that is dispatched on the {{domxref("ServiceWorkerGlobalScope")}} of a {{domxref("ServiceWorker")}}. As a child of {{domxref("ExtendableEvent")}}, it ensures that functional events such as {{domxref("FetchEvent")}} are not dispatched during installation.
This interface inherits from the {{domxref("ExtendableEvent")}} interface.
{{InheritanceDiagram}}
## Constructor
- {{domxref("InstallEvent.InstallEvent", "InstallEvent()")}} {{Deprecated_Inline}} {{Non-standard_Inline}}
- : Creates a new `InstallEvent` object.
## Instance properties
_Inherits properties from its ancestor, {{domxref("Event")}}_.
## Instance methods
_Inherits methods from its parent, {{domxref("ExtendableEvent")}}_.
## Examples
This code snippet is from the [service worker prefetch sample](https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/prefetch/service-worker.js) (see [prefetch running live](https://googlechrome.github.io/samples/service-worker/prefetch/).) The code calls {{domxref("ExtendableEvent.waitUntil", "ExtendableEvent.waitUntil()")}} in {{domxref("ServiceWorkerGlobalScope.install_event", "ServiceWorkerGlobalScope.oninstall")}} and delays treating the {{domxref("ServiceWorkerRegistration.installing")}} worker as installed until the passed promise resolves successfully. The promise resolves when all resources have been fetched and cached, or when any exception occurs.
The code snippet also shows a best practice for versioning caches used by the service worker. Although this example has only one cache, you can use this approach for multiple caches. The code maps a shorthand identifier for a cache to a specific, versioned cache name.
> **Note:** Logging statements are visible in Google Chrome via the "Inspect" interface for the relevant service worker accessed via chrome://serviceworker-internals.
```js
const CACHE_VERSION = 1;
const CURRENT_CACHES = {
prefetch: `prefetch-cache-v${CACHE_VERSION}`,
};
self.addEventListener("install", (event) => {
const urlsToPrefetch = [
"./static/pre_fetched.txt",
"./static/pre_fetched.html",
"https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif",
];
console.log(
"Handling install event. Resources to pre-fetch:",
urlsToPrefetch,
);
event.waitUntil(
caches
.open(CURRENT_CACHES["prefetch"])
.then((cache) => {
return cache
.addAll(
urlsToPrefetch.map((urlToPrefetch) => {
return new Request(urlToPrefetch, { mode: "no-cors" });
}),
)
.then(() => {
console.log("All resources have been fetched and cached.");
});
})
.catch((error) => {
console.error("Pre-fetching failed:", error);
}),
);
});
```
## Browser compatibility
{{Compat}}
## See also
- [`install` event](/en-US/docs/Web/API/ServiceWorkerGlobalScope/install_event)
- {{domxref("NotificationEvent")}}
- {{jsxref("Promise")}}
- [Fetch API](/en-US/docs/Web/API/Fetch_API)
| 0 |
data/mdn-content/files/en-us/web/api/installevent | data/mdn-content/files/en-us/web/api/installevent/installevent/index.md | ---
title: "InstallEvent: InstallEvent() constructor"
short-title: InstallEvent()
slug: Web/API/InstallEvent/InstallEvent
page-type: web-api-constructor
status:
- deprecated
- non-standard
browser-compat: api.InstallEvent.InstallEvent
---
{{APIRef("Service Workers API")}}{{Deprecated_Header}}{{Non-standard_header}}
The **`InstallEvent()`** constructor creates a new {{domxref("InstallEvent")}} object.
## Syntax
```js-nolint
new InstallEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `install`.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can contain any custom settings that you want to apply to the event object. Currently no possible options are mandatory, but this has been defined for forward compatibility.
## Return value
A new {{domxref("InstallEvent")}} object.
## Specifications
_This feature is no more on the standard track._
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Promise")}}
- [Fetch API](/en-US/docs/Web/API/Fetch_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfontfaceelement/index.md | ---
title: SVGFontFaceElement
slug: Web/API/SVGFontFaceElement
page-type: web-api-interface
status:
- deprecated
browser-compat: api.SVGFontFaceElement
---
{{APIRef("SVG")}}{{deprecated_header}}
The **`SVGFontFaceElement`** interface corresponds to the {{SVGElement("font-face")}} elements.
Object-oriented access to the attributes of the {{SVGElement("font-face")}} element via the SVG DOM is not possible.
{{InheritanceDiagram}}
## Instance properties
_This interface has no properties but inherits properties from its parent, {{domxref("SVGElement")}}._
## Instance methods
_This interface has no methods but inherits methods from its parent, {{domxref("SVGElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{SVGElement("font-face")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlcollection/index.md | ---
title: HTMLCollection
slug: Web/API/HTMLCollection
page-type: web-api-interface
browser-compat: api.HTMLCollection
---
{{APIRef("DOM")}}
The **`HTMLCollection`** interface represents a generic collection (array-like object similar to {{jsxref("Functions/arguments", "arguments")}}) of elements (in document order) and offers methods and properties for selecting from the list.
> **Note:** This interface is called `HTMLCollection` for historical reasons (before the modern DOM, collections implementing this interface could only have HTML elements as their items).
An `HTMLCollection` in the HTML DOM is live; it is automatically updated when the underlying document is changed. For this reason it is a good idea to make a copy (e.g., using {{jsxref("Array/from", "Array.from")}}) to iterate over if adding, moving, or removing nodes.
> **Note:** This interface was an [attempt to create an unmodifiable list](https://stackoverflow.com/questions/74630989/why-use-domstringlist-rather-than-an-array/74641156#74641156) and only continues to be supported to not break code that's already using it. Modern APIs use types that wrap around ECMAScript array types instead, so you can treat them like ECMAScript arrays, and at the same time impose additional semantics on their usage (such as making their items read-only).
## Instance properties
- {{domxref("HTMLCollection.length")}} {{ReadOnlyInline}}
- : Returns the number of items in the collection.
## Instance methods
- {{domxref("HTMLCollection.item()")}}
- : Returns the specific element at the given zero-based `index` into the list. Returns `null` if the `index` is out of range.
An alternative to accessing `collection[i]` (which instead returns `undefined` when `i` is out-of-bounds). This is mostly useful for non-JavaScript DOM implementations.
- {{domxref("HTMLCollection.namedItem()")}}
- : Returns the specific node whose ID or, as a fallback, name matches the string specified by `name`. Matching by name is only done as a last resort, only in HTML, and only if the referenced element supports the `name` attribute. Returns `null` if no node exists by the given name.
An alternative to accessing `collection[name]` (which instead returns `undefined` when `name` does not exist). This is mostly useful for non-JavaScript DOM implementations.
## Usage in JavaScript
`HTMLCollection` also exposes its members as properties by name and index. HTML IDs may contain `:` and `.` as valid characters, which would necessitate using bracket notation for property access. Currently, an `HTMLCollection` object does not recognize purely numeric IDs, which would cause conflict with the array-style access, though HTML does permit these.
For example, assuming there is one `<form>` element in the document and its `id` is `myForm`:
```js
let elem1, elem2;
// document.forms is an HTMLCollection
elem1 = document.forms[0];
elem2 = document.forms.item(0);
alert(elem1 === elem2); // shows: "true"
elem1 = document.forms.myForm;
elem2 = document.forms.namedItem("myForm");
alert(elem1 === elem2); // shows: "true"
elem1 = document.forms["named.item.with.periods"];
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("NodeList")}}
- {{domxref("HTMLFormControlsCollection")}}, {{domxref("HTMLOptionsCollection")}}
| 0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.