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/gpu | data/mdn-content/files/en-us/web/api/gpu/requestadapter/index.md | ---
title: "GPU: requestAdapter() method"
short-title: requestAdapter()
slug: Web/API/GPU/requestAdapter
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.GPU.requestAdapter
---
{{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}}
The **`requestAdapter()`** method of the
{{domxref("GPU")}} interface returns a {{jsxref("Promise")}} that fulfills with a {{domxref("GPUAdapter")}} object instance. From this you can request a {{domxref("GPUDevice")}}, adapter info, features, and limits.
Note that the user agent chooses whether to return an adapter. If so, it chooses according to the provided options. If no options are provided, the device will provide access to the default adapter, which is usually good enough for most purposes.
## Syntax
```js-nolint
requestAdapter()
requestAdapter(options)
```
### Parameters
- `options` {{optional_inline}}
- : An object containing the following properties:
- `powerPreference` {{optional_inline}}
- : An enumerated value that can be used to provide a hint to the user agent indicating what class of adapter should be chosen from the system's available adapters. Available values are:
- `undefined` (or not specified), which provides no hint.
- `"low-power"`, which provides a hint to prioritize power savings over performance. If your app runs OK with this setting, it is recommended to use it, as it can significantly improve battery life on portable devices. This is usually the default if no options are provided.
- `"high-performance"`, which provides a hint to prioritize performance over power consumption. You are encouraged to only specify this value if absolutely necessary, since it may significantly decrease battery life on portable devices. It may also result in increased {{domxref("GPUDevice")}} loss — the system will sometimes elect to switch to a lower-power adapter to save power.
This hint's primary purpose is to influence which GPU is used in a multi-GPU system. For instance, some laptops have a low-power integrated GPU and a high-performance discrete GPU. Different factors may affect which adapter is returned including battery status, attached displays, or removable GPUs.
> **Note:** On Chrome running on dual-GPU macOS devices, if `requestAdapter()` is called without a `powerPreference` option, the high-performance discrete GPU is returned when the user's device is on AC power. Otherwise, the low-power integrated GPU is returned.
### Fallback adapters
The adapter provided by the user agent may be a **fallback adapter**, if it determines it to be the most appropriate option available. A fallback adapter generally has significant performance caveats in exchange for some combination of wider compatibility, more predictable behavior, or improved privacy. For example, some browsers may offer a software-based implementation of the API via a fallback adapter. A fallback adapter will not be available on every system.
If you wish to prevent your apps from running on fallback adapters, you should check the {{domxref("GPUAdapter.isFallbackAdapter")}} attribute prior to requesting a {{domxref("GPUDevice")}}.
> **Note:** The specification includes a `forceFallbackAdapter` option for `requestAdapter()`. This is a boolean that, if set to `true`, forces the user agent to return a fallback adapter if one is available. This is not yet supported by any browser.
### Return value
A {{jsxref("Promise")}} that fulfills with a {{domxref("GPUAdapter")}} object instance if the request is successful.
`requestAdapter()` will resolve to `null` if an appropriate adapter is not available.
### Exceptions
None.
## Examples
```js
async function init() {
if (!navigator.gpu) {
throw Error("WebGPU not supported.");
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
throw Error("Couldn't request WebGPU adapter.");
}
const device = await adapter.requestDevice();
//...
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The [WebGPU API](/en-US/docs/Web/API/WebGPU_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/speechrecognitionresult/index.md | ---
title: SpeechRecognitionResult
slug: Web/API/SpeechRecognitionResult
page-type: web-api-interface
browser-compat: api.SpeechRecognitionResult
---
{{APIRef("Web Speech API")}}
The **`SpeechRecognitionResult`** interface of the [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) represents a single recognition match, which may contain multiple {{domxref("SpeechRecognitionAlternative")}} objects.
## Instance properties
- {{domxref("SpeechRecognitionResult.isFinal")}} {{ReadOnlyInline}}
- : A boolean value that states whether this result is final (true) or not (false) — if so, then this is the final time this result will be returned; if not, then this result is an interim result, and may be updated later on.
- {{domxref("SpeechRecognitionResult.length")}} {{ReadOnlyInline}}
- : Returns the length of the "array" — the number of {{domxref("SpeechRecognitionAlternative")}} objects contained in the result (also referred to as "n-best alternatives".)
## Instance methods
- {{domxref("SpeechRecognitionResult.item")}}
- : A standard getter that allows {{domxref("SpeechRecognitionAlternative")}} objects within the result to be accessed via array syntax.
## Examples
This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example.
```js
recognition.onresult = (event) => {
// The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
// The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
// It has a getter so it can be accessed like an array
// The first [0] returns the SpeechRecognitionResult at position 0.
// Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
// that contain individual results.
// These also have getters so they can be accessed like arrays.
// The second [0] returns the SpeechRecognitionAlternative at position 0.
// We then return the transcript property of the SpeechRecognitionAlternative object
const color = event.results[0][0].transcript;
diagnostic.textContent = `Result received: ${color}.`;
bg.style.backgroundColor = color;
};
```
## 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/speechrecognitionresult | data/mdn-content/files/en-us/web/api/speechrecognitionresult/isfinal/index.md | ---
title: "SpeechRecognitionResult: isFinal property"
short-title: isFinal
slug: Web/API/SpeechRecognitionResult/isFinal
page-type: web-api-instance-property
browser-compat: api.SpeechRecognitionResult.isFinal
---
{{APIRef("Web Speech API")}}
The **`isFinal`** read-only property of the
{{domxref("SpeechRecognitionResult")}} interface is a boolean value that states
whether this result is final (`true`) or not (`false`) — if so,
then this is the final time this result will be returned; if not, then this result is an
interim result, and may be updated later on.
## Value
A boolean value.
## Examples
```js
recognition.onresult = (event) => {
// The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
// The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
// It has a getter so it can be accessed like an array
// The first [0] returns the SpeechRecognitionResult at position 0.
// Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
// that contain individual results.
// These also have getters so they can be accessed like arrays.
// The second [0] returns the SpeechRecognitionAlternative at position 0.
// We then return the transcript property of the SpeechRecognitionAlternative object
const color = event.results[0][0].transcript;
diagnostic.textContent = `Result received: ${color}.`;
bg.style.backgroundColor = color;
console.log(event.results[0].isFinal);
};
```
## 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/speechrecognitionresult | data/mdn-content/files/en-us/web/api/speechrecognitionresult/length/index.md | ---
title: "SpeechRecognitionResult: length property"
short-title: length
slug: Web/API/SpeechRecognitionResult/length
page-type: web-api-instance-property
browser-compat: api.SpeechRecognitionResult.length
---
{{APIRef("Web Speech API")}}
The **`length`** read-only property of the
{{domxref("SpeechRecognitionResult")}} interface returns the length of the "array"
— the number of {{domxref("SpeechRecognitionAlternative")}} objects contained
in the result (also referred to as "n-best alternatives".)
The number of alternatives contained in the result depends on what the
{{domxref("SpeechRecognition.maxAlternatives")}} property was set to when the speech
recognition was first initiated.
## Value
A number.
## Examples
This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example.
```js
recognition.onresult = (event) => {
// The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
// The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
// It has a getter so it can be accessed like an array
// The first [0] returns the SpeechRecognitionResult at position 0.
// Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
// that contain individual results.
// These also have getters so they can be accessed like arrays.
// The second [0] returns the SpeechRecognitionAlternative at position 0.
// We then return the transcript property of the SpeechRecognitionAlternative object
const color = event.results[0][0].transcript;
diagnostic.textContent = `Result received: ${color}.`;
bg.style.backgroundColor = color;
console.log(event.results[0].length);
};
```
## 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/speechrecognitionresult | data/mdn-content/files/en-us/web/api/speechrecognitionresult/item/index.md | ---
title: "SpeechRecognitionResult: item() method"
short-title: item()
slug: Web/API/SpeechRecognitionResult/item
page-type: web-api-instance-method
browser-compat: api.SpeechRecognitionResult.item
---
{{APIRef("Web Speech API")}}
The **`item`** getter of the
{{domxref("SpeechRecognitionResult")}} interface is a standard getter that allows
{{domxref("SpeechRecognitionAlternative")}} objects within the result to be accessed via
array syntax.
## Syntax
```js-nolint
item(index)
```
### Parameters
- `index`
- : Index of the item to retrieve.
### Return value
A {{domxref("SpeechRecognitionAlternative")}} object.
## Examples
This code is excerpted from our [Speech color changer](https://github.com/mdn/dom-examples/blob/main/web-speech-api/speech-color-changer/script.js) example.
```js
recognition.onresult = (event) => {
// The SpeechRecognitionEvent results property returns a SpeechRecognitionResultList object
// The SpeechRecognitionResultList object contains SpeechRecognitionResult objects.
// It has a getter so it can be accessed like an array
// The first [0] returns the SpeechRecognitionResult at position 0.
// Each SpeechRecognitionResult object contains SpeechRecognitionAlternative objects
// that contain individual results.
// These also have getters so they can be accessed like arrays.
// The second [0] returns the SpeechRecognitionAlternative at position 0.
// We then return the transcript property of the SpeechRecognitionAlternative object
const color = event.results[0][0].transcript;
diagnostic.textContent = `Result received: ${color}.`;
bg.style.backgroundColor = color;
};
```
## 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/blobevent/index.md | ---
title: BlobEvent
slug: Web/API/BlobEvent
page-type: web-api-interface
browser-compat: api.BlobEvent
---
{{APIRef("MediaStream Recording")}}
The **`BlobEvent`** interface of the [MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API) represents events associated with a {{domxref("Blob")}}. These blobs are typically, but not necessarily, associated with media content.
{{InheritanceDiagram}}
## Constructor
- {{domxref("BlobEvent.BlobEvent", "BlobEvent()")}}
- : Creates a `BlobEvent` event with the given parameters.
## Instance properties
_Inherits properties from its parent {{domxref("Event")}}_.
- {{domxref("BlobEvent.data")}} {{ReadOnlyInline}}
- : A {{domxref("Blob")}} representing the data associated with the event. The event was fired on the {{domxref("EventTarget")}} because of something happening on that specific {{domxref("Blob")}}.
- {{domxref("BlobEvent.timecode")}} {{ReadOnlyInline}}
- : A {{domxref("DOMHighResTimeStamp")}} indicating the difference between the timestamp of the first chunk in data and the timestamp of the first chunk in the first BlobEvent produced by this recorder. Note that the timecode in the first produced BlobEvent does not need to be zero.
## Instance methods
_No specific method; inherits methods from its parent {{domxref("Event")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("Event")}} base interface.
- [MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API): Sends `BlobEvent` objects each time a chunk of media is ready.
- [Using the MediaStream Recording API](/en-US/docs/Web/API/MediaStream_Recording_API/Using_the_MediaStream_Recording_API)
| 0 |
data/mdn-content/files/en-us/web/api/blobevent | data/mdn-content/files/en-us/web/api/blobevent/data/index.md | ---
title: "BlobEvent: data property"
short-title: data
slug: Web/API/BlobEvent/data
page-type: web-api-instance-property
browser-compat: api.BlobEvent.data
---
{{APIRef("MediaStream Recording")}}
The **`data`** read-only property of the {{domxref("BlobEvent")}} interface represents a {{domxref("Blob")}} associated with the event.
## Value
A {{domxref("Blob")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("BlobEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/blobevent | data/mdn-content/files/en-us/web/api/blobevent/blobevent/index.md | ---
title: "BlobEvent: BlobEvent() constructor"
short-title: BlobEvent()
slug: Web/API/BlobEvent/BlobEvent
page-type: web-api-constructor
browser-compat: api.BlobEvent.BlobEvent
---
{{APIRef("MediaStream Recording")}}
The **`BlobEvent()`** constructor returns a newly created
{{domxref("BlobEvent")}} object with an associated {{domxref("Blob")}}.
## Syntax
```js-nolint
new BlobEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers always set it to `dataavailable`.
- `options`
- : An object that, _in addition of the properties defined in {{domxref("Event/Event", "Event()")}}_, can have the following properties:
- `data`
- : The {{domxref("Blob")}} associated with the event.
- `timecode` {{optional_inline}}
- : A {{domxref("DOMHighResTimeStamp")}} to be used in initializing the blob event.
### Return value
A new {{domxref("BlobEvent")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("BlobEvent")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/blobevent | data/mdn-content/files/en-us/web/api/blobevent/timecode/index.md | ---
title: "BlobEvent: timecode property"
short-title: timecode
slug: Web/API/BlobEvent/timecode
page-type: web-api-instance-property
browser-compat: api.BlobEvent.timecode
---
{{APIRef("MediaStream Recording")}}
The **`timecode`** read-only property of the {{domxref("BlobEvent")}} interface indicates the difference between the timestamp of the first chunk of data, and the timestamp of the first chunk in the first `BlobEvent` produced by this recorder.
Note that the `timecode` in the first produced `BlobEvent` does not need to be zero.
## Value
A {{domxref("DOMHighResTimeStamp")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/url/index.md | ---
title: URL
slug: Web/API/URL
page-type: web-api-interface
browser-compat: api.URL
---
{{APIRef("URL API")}}
The **`URL`** interface is used to parse, construct, normalize, and encode {{glossary("URL", "URLs")}}. It works by providing properties which allow you to easily read and modify the components of a URL.
You normally create a new `URL` object by specifying the URL as a string when calling its constructor, or by providing a relative URL and a base URL. You can then easily read the parsed components of the URL or make changes to the URL.
If a browser doesn't yet support the {{domxref("URL.URL", "URL()")}} constructor, you can access a URL object using the {{domxref("Window")}} interface's {{domxref("URL")}} property. Be sure to check to see if any of your target browsers require this to be prefixed.
{{AvailableInWorkers}}
## Constructor
- {{domxref("URL.URL", "URL()")}}
- : Creates and returns a `URL` object referencing the URL specified using an absolute URL string, or a relative URL string and a base URL string.
## Instance properties
- {{domxref("URL.hash", "hash")}}
- : A string containing a `'#'` followed by the fragment identifier of the URL.
- {{domxref("URL.host", "host")}}
- : A string containing the domain (that is the _hostname_) followed by (if a port was specified) a `':'` and the _port_ of the URL.
- {{domxref("URL.hostname", "hostname")}}
- : A string containing the domain of the URL.
- {{domxref("URL.href", "href")}}
- : A {{Glossary("stringifier")}} that returns a string containing the whole URL.
- {{domxref("URL.origin", "origin")}} {{ReadOnlyInline}}
- : Returns a string containing the origin of the URL, that is its scheme, its domain and its port.
- {{domxref("URL.password", "password")}}
- : A string containing the password specified before the domain name.
- {{domxref("URL.pathname", "pathname")}}
- : A string containing an initial `'/'` followed by the path of the URL, not including the query string or fragment.
- {{domxref("URL.port", "port")}}
- : A string containing the port number of the URL.
- {{domxref("URL.protocol", "protocol")}}
- : A string containing the protocol scheme of the URL, including the final `':'`.
- {{domxref("URL.search", "search")}}
- : A string indicating the URL's parameter string; if any parameters are provided, this string includes all of them, beginning with the leading `?` character.
- {{domxref("URL.searchParams", "searchParams")}} {{ReadOnlyInline}}
- : A {{domxref("URLSearchParams")}} object which can be used to access the individual query parameters found in `search`.
- {{domxref("URL.username","username")}}
- : A string containing the username specified before the domain name.
## Static methods
- {{domxref("URL.canParse_static", "canParse()")}}
- : Returns a boolean indicating whether or not a URL defined from a URL string and optional base URL string is parsable and valid.
- {{domxref("URL.createObjectURL_static", "createObjectURL()")}}
- : Returns a string containing a unique blob URL, that is a URL with `blob:` as its scheme, followed by an opaque string uniquely identifying the object in the browser.
- {{domxref("URL.revokeObjectURL_static", "revokeObjectURL()")}}
- : Revokes an object URL previously created using {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}.
## Instance methods
- {{domxref("URL.toString", "toString()")}}
- : Returns a string containing the whole URL. It is a synonym for {{domxref("URL.href")}}, though it can't be used to modify the value.
- {{domxref("URL.toJSON", "toJSON()")}}
- : Returns a string containing the whole URL. It returns the same string as the `href` property.
## Usage notes
The constructor takes a `url` parameter, and an optional `base` parameter to use as a base if the `url` parameter is a relative URL:
```js
const url = new URL("../cats", "http://www.example.com/dogs");
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"
```
The constructor will raise an exception if the URL cannot be parsed to a valid URL.
You can either call the above code in a [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) block or use the {{domxref("URL.canParse_static", "canParse()")}} static method to first check the URL is valid:
```js
if (URL.canParse("../cats", "http://www.example.com/dogs")) {
const url = new URL("../cats", "http://www.example.com/dogs");
console.log(url.hostname); // "www.example.com"
console.log(url.pathname); // "/cats"
} else {
console.log("Invalid URL"); //Invalid URL
}
```
URL properties can be set to construct the URL:
```js
url.hash = "tabby";
console.log(url.href); // "http://www.example.com/cats#tabby"
```
URLs are encoded according to the rules found in {{RFC(3986)}}. For instance:
```js
url.pathname = "démonstration.html";
console.log(url.href); // "http://www.example.com/d%C3%A9monstration.html"
```
The {{domxref("URLSearchParams")}} interface can be used to build and manipulate the URL query string.
To get the search params from the current window's URL, you can do this:
```js
// https://some.site/?id=123
const parsedUrl = new URL(window.location.href);
console.log(parsedUrl.searchParams.get("id")); // "123"
```
The {{domxref("URL.toString", "toString()")}} method of `URL` just returns the value of the {{domxref("URL.href", "href")}} property, so the constructor can be used to normalize and encode a URL directly.
```js
const response = await fetch(
new URL("http://www.example.com/démonstration.html"),
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `URL` in `core-js`](https://github.com/zloirock/core-js#url-and-urlsearchparams)
- [URL API](/en-US/docs/Web/API/URL_API)
- [What is a URL?](/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL)
- Property to obtain a `URL` object: {{domxref("URL")}}.
- {{domxref("URLSearchParams")}}.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/origin/index.md | ---
title: "URL: origin property"
short-title: origin
slug: Web/API/URL/origin
page-type: web-api-instance-property
browser-compat: api.URL.origin
---
{{APIRef("URL API")}}
The **`origin`** read-only property of
the {{domxref("URL")}} interface returns a string containing the
Unicode serialization of the origin of the represented URL.
The exact structure
varies depending on the type of URL:
- For `http` or `https` URLs, the scheme followed by
`'://'`, followed by the domain, followed by `':'`, followed by
the port (if explicitly specified, unless it is the default port - `80` and `443` respectively).
- For `file:` URLs, the value is browser dependent.
- for `blob:` URLs, the origin of the URL following `blob:` will
be used. For example, `"blob:https://mozilla.org"` will be returned as
`"https://mozilla.org".`
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
const url = new URL("blob:https://mozilla.org:443/");
console.log(url.origin); // Logs 'https://mozilla.org'
const url = new URL("http://localhost:80/");
console.log(url.origin); // Logs 'http://localhost'
const url = new URL("https://mozilla.org:8080/");
console.log(url.origin); // Logs 'https://mozilla.org:8080'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/searchparams/index.md | ---
title: "URL: searchParams property"
short-title: searchParams
slug: Web/API/URL/searchParams
page-type: web-api-instance-property
browser-compat: api.URL.searchParams
---
{{APIRef("URL API")}}
The **`searchParams`** read-only property of the
{{domxref("URL")}} interface returns a {{domxref("URLSearchParams")}} object allowing
access to the {{httpmethod("GET")}} decoded query arguments contained in the URL.
{{AvailableInWorkers}}
## Value
A {{domxref("URLSearchParams")}} object.
## Examples
If the URL of your page is
`https://example.com/?name=Jonathan%20Smith&age=18` you could parse out
the `name` and `age` parameters using:
```js
let params = new URL(document.location).searchParams;
let name = params.get("name"); // is the string "Jonathan Smith".
let age = parseInt(params.get("age")); // is the number 18
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/createobjecturl_static/index.md | ---
title: "URL: createObjectURL() static method"
short-title: createObjectURL()
slug: Web/API/URL/createObjectURL_static
page-type: web-api-static-method
browser-compat: api.URL.createObjectURL_static
---
{{APIRef("File API")}}
The **`URL.createObjectURL()`** static
method creates a string containing a URL representing the object
given in the parameter.
The URL lifetime is tied to the {{domxref("document")}}
in the window on which it was created. The new object URL represents the specified
{{domxref("File")}} object or {{domxref("Blob")}} object.
To release an object URL, call {{domxref("URL.revokeObjectURL_static", "revokeObjectURL()")}}.
{{AvailableInWorkers("notservice")}}
> **Note:** This feature is _not_ available in [Service Workers](/en-US/docs/Web/API/Service_Worker_API) due to its
> potential to create memory leaks.
## Syntax
```js-nolint
URL.createObjectURL(object)
```
### Parameters
- `object`
- : A {{domxref("File")}}, {{domxref("Blob")}}, or {{domxref("MediaSource")}} object to
create an object URL for.
### Return value
A string containing an object URL that can be used to reference the
contents of the specified source `object`.
## Examples
See [Using object URLs to display images](/en-US/docs/Web/API/File_API/Using_files_from_web_applications#example_using_object_urls_to_display_images).
## Usage notes
### Memory management
Each time you call `createObjectURL()`, a new object URL is created, even if
you've already created one for the same object. Each of these must be released by
calling {{domxref("URL.revokeObjectURL_static", "URL.revokeObjectURL()")}} when you no longer need them.
Browsers will release object URLs automatically when the document is unloaded; however,
for optimal performance and memory usage, if there are safe times when you can
explicitly unload them, you should do so.
### Using object URLs for media streams
In older versions of the Media Source specification, attaching a stream to a
{{HTMLElement("video")}} element required creating an object URL for the
{{domxref("MediaStream")}}. This is no longer necessary, and browsers are removing
support for doing this.
> **Warning:** If you still have code that relies on
> {{domxref("URL.createObjectURL_static", "createObjectURL()")}} to attach streams to media
> elements, you need to update your code to set {{domxref("HTMLMediaElement.srcObject", "srcObject")}} to the `MediaStream` directly.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications)
- [Using object URLs to display images](/en-US/docs/Web/API/File_API/Using_files_from_web_applications#example_using_object_urls_to_display_images)
- {{domxref("URL.revokeObjectURL_static", "URL.revokeObjectURL()")}}
- {{domxref("HTMLMediaElement.srcObject")}}
- {{domxref("FileReader.readAsDataURL()")}}
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/tostring/index.md | ---
title: "URL: toString() method"
short-title: toString()
slug: Web/API/URL/toString
page-type: web-api-instance-method
browser-compat: api.URL.toString
---
{{ApiRef("URL API")}}
The **`toString()`** method of the {{domxref("URL")}} interface returns a
string containing the whole URL. It is effectively a read-only version
of {{domxref("URL.href")}}.
{{AvailableInWorkers}}
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
A string.
## Examples
```js
const url = new URL(
"https://developer.mozilla.org/en-US/docs/Web/API/URL/toString",
);
url.toString(); // should return the URL as a string
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/username/index.md | ---
title: "URL: username property"
short-title: username
slug: Web/API/URL/username
page-type: web-api-instance-property
browser-compat: api.URL.username
---
{{ApiRef("URL API")}}
The **`username`** property of the {{domxref("URL")}} interface
is a string containing the username specified before the domain name.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
const url = new URL(
"https://anonymous:[email protected]/en-US/docs/Web/API/URL/username",
);
console.log(url.username); // Logs "anonymous"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/search/index.md | ---
title: "URL: search property"
short-title: search
slug: Web/API/URL/search
page-type: web-api-instance-property
browser-compat: api.URL.search
---
{{ApiRef("URL API")}}
The **`search`** property of the {{domxref("URL")}} interface
is a search string, also called a _query string_, that is a
string containing a `'?'` followed by the parameters of the
URL.
Modern browsers provide the {{domxref("URL.searchParams")}} property to make it easy to
parse out the parameters from the query string.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
const url = new URL(
"https://developer.mozilla.org/en-US/docs/Web/API/URL/search?q=123",
);
console.log(url.search); // Logs "?q=123"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/port/index.md | ---
title: "URL: port property"
short-title: port
slug: Web/API/URL/port
page-type: web-api-instance-property
browser-compat: api.URL.port
---
{{ApiRef("URL API")}}
The **`port`** property of the {{domxref("URL")}} interface is
a string containing the port number of the URL.
> **Note:** If an input string passed to the [`URL()`](/en-US/docs/Web/API/URL/URL) constructor doesn't contain an explicit port number (e.g., `https://localhost`) or contains a port number that's the default port number corresponding to the protocol part of the input string (e.g., `https://localhost:443`), then in the [`URL`](/en-US/docs/Web/API/URL) object the constructor returns, the value of the port property will be the empty string: `''`.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
// https protocol with non-default port number
new URL("https://example.com:5443/svn/Repos/").port; // '5443'
// http protocol with non-default port number
new URL("http://example.com:8080/svn/Repos/").port; // '8080'
// https protocol with default port number
new URL("https://example.com:443/svn/Repos/").port; // '' (empty string)
// http protocol with default port number
new URL("http://example.com:80/svn/Repos/").port; // '' (empty string)
// https protocol with no explicit port number
new URL("https://example.com/svn/Repos/").port; // '' (empty string)
// http protocol with no explicit port number
new URL("https://example.com/svn/Repos/").port; // '' (empty string)
// ftp protocol with non-default port number
new URL("ftp://example.com:221/svn/Repos/").port; // '221'
// ftp protocol with default port number
new URL("ftp://example.com:21/svn/Repos/").port; // '' (empty string)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/hash/index.md | ---
title: "URL: hash property"
short-title: hash
slug: Web/API/URL/hash
page-type: web-api-instance-property
browser-compat: api.URL.hash
---
{{ APIRef("URL API") }}
The **`hash`** property of the
{{domxref("URL")}} interface is a string containing a
`'#'` followed by the fragment identifier of the URL.
The fragment is not [URL decoded](https://en.wikipedia.org/wiki/URL_encoding). If the URL does not
have a fragment identifier, this property contains an empty string — `""`.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
const url = new URL(
"https://developer.mozilla.org/en-US/docs/Web/API/URL/href#Examples",
);
console.log(url.hash); // Logs: '#Examples'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/pathname/index.md | ---
title: "URL: pathname property"
short-title: pathname
slug: Web/API/URL/pathname
page-type: web-api-instance-property
browser-compat: api.URL.pathname
---
{{ApiRef("URL API")}}
The **`pathname`** property of the {{domxref("URL")}} interface represents a location in a hierarchical structure. It is a string constructed from a list of path segments, each of which is prefixed by a `/` character. If the URL has no path segments, the value of its `pathname` property will be the empty string.
URLs such as `https` and `http` URLs that have [hierarchical schemes](https://www.rfc-editor.org/rfc/rfc3986#section-1.2.3) (which the URL standard calls "[special schemes](https://url.spec.whatwg.org/#special-scheme)") always have at least one (invisible) path segment: the empty string. Thus the `pathname` value for such "special scheme" URLs can never be the empty string, but will instead always have a least one `/` character.
For example, the URL `https://developer.mozilla.org` has just one path segment: the empty string, so its `pathname` value is constructed by prefixing a `/` character to the empty string.
Some systems define the term _slug_ to mean the final segment of a non-empty path if it identifies a page in human-readable keywords. For example, the URL `https://example.org/articles/this-that-other-outre-collection` has `this-that-other-outre-collection` as its slug.
Some systems use the `;` and `=` characters to delimit parameters and parameter values applicable to a path segment. For example, with the URL `https://example.org/users;id=42/tasks;state=open?sort=modified`, a system might extract and use the path segment parameters `id=42` and `state=open` from the path segments `users;id=42` and `tasks;state=open`.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
const url = new URL(
"https://developer.mozilla.org/en-US/docs/Web/API/URL/pathname?q=value",
);
console.log(url.pathname); // Logs "/en-US/docs/Web/API/URL/pathname"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/canparse_static/index.md | ---
title: "URL: canParse() static method"
short-title: canParse()
slug: Web/API/URL/canParse_static
page-type: web-api-static-method
browser-compat: api.URL.canParse_static
---
{{ApiRef("URL API")}}
The **`URL.canParse()`** static method of the {{domxref("URL")}} interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid.
This is a fast and easy alternative to constructing a `URL` within a [try...catch](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) block.
It returns `true` for the same values for which the [`URL()` constructor](/en-US/docs/Web/API/URL/URL) would succeed, and `false` for the values that would cause the constructor to throw.
## Syntax
```js-nolint
URL.canParse(url)
URL.canParse(url, base)
```
### Parameters
- `url`
- : A string or any other object with a {{Glossary("stringifier")}} — including, for example, an {{htmlelement("a")}} or {{htmlelement("area")}} element — that represents an absolute or relative URL.
If `url` is a relative URL, `base` is required, and will be used as the base URL.
If `url` is an absolute URL, a given `base` will be ignored.
- `base` {{optional_inline}}
- : A string representing the base URL to use in cases where `url` is a relative URL.
If not specified, it defaults to `undefined`.
> **Note:** The `url` and `base` arguments will each be stringified from whatever value you pass, just like with other Web APIs that accept a string.
> In particular, you can use an existing {{domxref("URL")}} object for either argument, and it will be stringified to the object's {{domxref("URL.href", "href")}} property.
### Return value
`true` if the URL can be parsed and is valid; `false` otherwise.
## Examples
This live example demonstrates how to use the `URL.canParse()` static method for a few different absolute and relative URL values.
The first part of the example defines an HTML `<pre>` element to log to, along with a logging method `log()`.
```html
<pre id="log"></pre>
```
```js
const logElement = document.getElementById("log");
function log(text) {
logElement.innerText += `${text}\n`;
}
```
Next we check that the `URL.canParse()` method is supported using the condition `"canParse" in URL`.
If the method is supported we log the result of checking an absolute URL, a relative URL with no base URL, and a relative URL with a valid base URL.
We also log the case when `URL.canParse()` is not supported.
```js
if ("canParse" in URL) {
log("Test valid absolute URL");
let url = "https://developer.mozilla.org/";
let result = URL.canParse(url);
log(` URL.canParse("${url}"): ${result}`);
log("\nTest relative URL with no base URL");
url = "/en-US/docs";
result = URL.canParse(url);
log(` URL.canParse("${url}"): ${result}`);
log("\nTest relative URL with valid base URL");
let baseUrl = "https://developer.mozilla.org/";
result = URL.canParse(url, baseUrl);
log(` URL.canParse("${url}","${baseUrl}"): ${result}`);
} else {
log("URL.canParse() not supported");
}
```
Last of all, the code below shows that the `baseUrl` doesn't have to be a string.
Here we have passed a `URL` object.
```js
if ("canParse" in URL) {
log("\nTest relative URL with base URL supplied as a URL object");
let baseUrl = new URL("https://developer.mozilla.org/");
let url = "/en-US/docs";
result = URL.canParse(url, baseUrl);
log(` URL.canParse("${url}","${baseUrl}"): ${result}`);
}
```
The results of each of the checks are shown below.
{{EmbedLiveSample('Examples', '100%', '200')}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("URL.URL", "URL()")}}
- [A polyfill of `URL.canParse()`](https://github.com/zloirock/core-js#url-and-urlsearchparams) is available in [`core-js`](https://github.com/zloirock/core-js)
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/hostname/index.md | ---
title: "URL: hostname property"
short-title: hostname
slug: Web/API/URL/hostname
page-type: web-api-instance-property
browser-compat: api.URL.hostname
---
{{ApiRef("URL API")}}
The **`hostname`** property of the {{domxref("URL")}} interface
is a string containing the {{glossary("domain name")}} of the URL.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
const url = new URL(
"https://developer.mozilla.org/en-US/docs/Web/API/URL/hostname",
);
console.log(url.hostname); // Logs: 'developer.mozilla.org'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/url/index.md | ---
title: "URL: URL() constructor"
short-title: URL()
slug: Web/API/URL/URL
page-type: web-api-constructor
browser-compat: api.URL.URL
---
{{APIRef("URL API")}}
The **`URL()`** constructor returns a newly created
{{domxref("URL")}} object representing the URL defined by the parameters.
If the given base URL or the resulting URL are not valid URLs, the JavaScript
{{jsxref("TypeError")}} exception is thrown.
{{AvailableInWorkers}}
## Syntax
```js-nolint
new URL(url)
new URL(url, base)
```
### Parameters
- `url`
- : A string or any other object with a {{Glossary("stringifier")}} — including, for example, an {{htmlelement("a")}} or {{htmlelement("area")}} element — that represents an absolute or relative URL.
If `url` is a relative URL, `base` is
required, and will be used as the base URL. If `url` is an
absolute URL, a given `base` will be ignored.
- `base` {{optional_inline}}
- : A string representing the base URL to use in cases where
`url` is a relative URL. If not specified, it defaults to
`undefined`.
> **Note:** The `url` and `base` arguments will
> each be stringified from whatever value you pass, just like with other Web APIs
> that accept a string. In particular, you can use an existing
> {{domxref("URL")}} object for either argument, and it will stringify to the
> object's {{domxref("URL.href", "href")}} property.
### Exceptions
| Exception | Explanation |
| ----------------------- | --------------------------------------------------------------------------------------------------------- |
| {{jsxref("TypeError")}} | `url` (in the case of absolute URLs) or `base` + `url` (in the case of relative URLs) is not a valid URL. |
## Examples
```js
// Base URLs:
let baseUrl = "https://developer.mozilla.org";
let A = new URL("/", baseUrl);
// => 'https://developer.mozilla.org/'
let B = new URL(baseUrl);
// => 'https://developer.mozilla.org/'
new URL("en-US/docs", B);
// => 'https://developer.mozilla.org/en-US/docs'
let D = new URL("/en-US/docs", B);
// => 'https://developer.mozilla.org/en-US/docs'
new URL("/en-US/docs", D);
// => 'https://developer.mozilla.org/en-US/docs'
new URL("/en-US/docs", A);
// => 'https://developer.mozilla.org/en-US/docs'
new URL("/en-US/docs", "https://developer.mozilla.org/fr-FR/toto");
// => 'https://developer.mozilla.org/en-US/docs'
// Invalid URLs:
new URL("/en-US/docs", "");
// Raises a TypeError exception as '' is not a valid URL
new URL("/en-US/docs");
// Raises a TypeError exception as '/en-US/docs' is not a valid URL
// Other cases:
new URL("http://www.example.com");
// => 'http://www.example.com/'
new URL("http://www.example.com", B);
// => 'http://www.example.com/'
new URL("", "https://example.com/?query=1");
// => 'https://example.com/?query=1' (Edge before 79 removes query arguments)
new URL("/a", "https://example.com/?query=1");
// => 'https://example.com/a' (see relative URLs)
new URL("//foo.com", "https://example.com");
// => 'https://foo.com/' (see relative URLs)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `URL` in `core-js`](https://github.com/zloirock/core-js#url-and-urlsearchparams)
- The interface it belongs to: {{domxref("URL")}}.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/host/index.md | ---
title: "URL: host property"
short-title: host
slug: Web/API/URL/host
page-type: web-api-instance-property
browser-compat: api.URL.host
---
{{ApiRef("URL API")}}
The **`host`** property of the {{domxref("URL")}} interface is
a string containing the host, that is the {{domxref("URL.hostname",
"hostname")}}, and then, if the {{glossary("port")}} of the URL is nonempty, a
`':'`, followed by the {{domxref("URL.port", "port")}} of the URL.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
let url = new URL("https://developer.mozilla.org/en-US/docs/Web/API/URL/host");
console.log(url.host); // "developer.mozilla.org"
url = new URL("https://developer.mozilla.org:443/en-US/docs/Web/API/URL/host");
console.log(url.host); // "developer.mozilla.org"
// The port number is not included because 443 is the scheme's default port
url = new URL("https://developer.mozilla.org:4097/en-US/docs/Web/API/URL/host");
console.log(url.host); // "developer.mozilla.org:4097"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/href/index.md | ---
title: "URL: href property"
short-title: href
slug: Web/API/URL/href
page-type: web-api-instance-property
browser-compat: api.URL.href
---
{{ApiRef("URL API")}}
The **`href`** property of the {{domxref("URL")}} interface is
a string containing the whole URL.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
const url = new URL(
"https://developer.mozilla.org/en-US/docs/Web/API/URL/href",
);
console.log(url.href); // Logs: 'https://developer.mozilla.org/en-US/docs/Web/API/URL/href'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/password/index.md | ---
title: "URL: password property"
short-title: password
slug: Web/API/URL/password
page-type: web-api-instance-property
browser-compat: api.URL.password
---
{{ApiRef("URL API")}}
The **`password`** property of the {{domxref("URL")}} interface
is a string containing the password specified before the domain name.
If it is set without first setting the {{domxref("URL.username", "username")}}
property, it silently fails.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
const url = new URL(
"https://anonymous:[email protected]/en-US/docs/Web/API/URL/password",
);
console.log(url.password); // Logs "flabada"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/protocol/index.md | ---
title: "URL: protocol property"
short-title: protocol
slug: Web/API/URL/protocol
page-type: web-api-instance-property
browser-compat: api.URL.protocol
---
{{ApiRef("URL API")}}
The **`protocol`** property of the {{domxref("URL")}} interface
is a string representing the protocol scheme of the URL, including the
final `':'`.
{{AvailableInWorkers}}
## Value
A string.
## Examples
```js
const url = new URL(
"https://developer.mozilla.org/en-US/docs/Web/API/URL/protocol",
);
console.log(url.protocol); // Logs "https:"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("URL")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/revokeobjecturl_static/index.md | ---
title: "URL: revokeObjectURL() static method"
short-title: revokeObjectURL()
slug: Web/API/URL/revokeObjectURL_static
page-type: web-api-static-method
browser-compat: api.URL.revokeObjectURL_static
---
{{ApiRef("File API")}}
The **`URL.revokeObjectURL()`** static
method releases an existing object URL which was previously created by calling
{{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}.
Call this method when you've finished
using an object URL to let the browser know not to keep the reference to the file any
longer.
{{AvailableInWorkers("notservice")}}
> **Note:** This method is _not_ available in [Service Workers](/en-US/docs/Web/API/Service_Worker_API), due to
> issues with the {{domxref("Blob")}} interface's life cycle and the potential for leaks.
## Syntax
```js-nolint
URL.revokeObjectURL(objectURL)
```
### Parameters
- `objectURL`
- : A string representing an object URL that was previously created by
calling {{domxref("URL.createObjectURL_static", "createObjectURL()")}}.
### Return value
None ({{jsxref("undefined")}}).
## Examples
See [Using object URLs to display images](/en-US/docs/Web/API/File_API/Using_files_from_web_applications#example_using_object_urls_to_display_images).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using files from web applications](/en-US/docs/Web/API/File_API/Using_files_from_web_applications)
- [Using object URLs to display images](/en-US/docs/Web/API/File_API/Using_files_from_web_applications#example_using_object_urls_to_display_images)
- {{domxref("URL.createObjectURL_static", "URL.createObjectURL()")}}
| 0 |
data/mdn-content/files/en-us/web/api/url | data/mdn-content/files/en-us/web/api/url/tojson/index.md | ---
title: "URL: toJSON() method"
short-title: toJSON()
slug: Web/API/URL/toJSON
page-type: web-api-instance-method
browser-compat: api.URL.toJSON
---
{{APIRef("URL API")}}
The **`toJSON()`** method of the {{domxref("URL")}} interface
returns a string containing a serialized version of the URL,
although in practice it seems to have the same effect as
{{domxref("URL.toString()")}}.
{{AvailableInWorkers}}
## Syntax
```js-nolint
toJSON()
```
### Parameters
None.
### Return value
A string.
## Examples
```js
const url = new URL(
"https://developer.mozilla.org/en-US/docs/Web/API/URL/toString",
);
url.toJSON(); // should return the URL as a string
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `URL.prototype.toJSON` in `core-js`](https://github.com/zloirock/core-js#url-and-urlsearchparams)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/screen_orientation_api/index.md | ---
title: Screen Orientation API
slug: Web/API/Screen_Orientation_API
page-type: web-api-overview
browser-compat: api.ScreenOrientation
---
{{DefaultAPISidebar("Screen Orientation API")}}
The **Screen Orientation API** provides information about the orientation of the screen.
## Interfaces
- {{DOMxRef("ScreenOrientation")}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/xmldocument/index.md | ---
title: XMLDocument
slug: Web/API/XMLDocument
page-type: web-api-interface
browser-compat: api.XMLDocument
---
{{APIRef("DOM")}}
The **XMLDocument** interface represents an XML document. It inherits from the generic {{DOMxRef("Document")}} and does not add any specific methods or properties to it: nevertheless, several algorithms behave differently with the two types of documents.
{{InheritanceDiagram}}
## Property
_Also inherits properties from: {{DOMxRef("Document")}}_.
## Instance methods
_Also inherits methods from: {{DOMxRef("Document")}}_.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [The Document Object Model (DOM)](/en-US/docs/Web/API/Document_Object_Model)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/contact_picker_api/index.md | ---
title: Contact Picker API
slug: Web/API/Contact_Picker_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.ContactsManager
---
{{securecontext_header}}{{DefaultAPISidebar("Contact Picker API")}}{{SeeCompatTable}}
The Contact Picker API allows users to select entries from their contact list and share limited details of the selected entries with a website or application.
> **Note:** This API is _not available_ in [Web Workers](/en-US/docs/Web/API/Web_Workers_API) (not exposed via {{domxref("WorkerNavigator")}}).
## Contact Picker API Concepts and Usage
Access to contacts has long been a feature available within native applications. The Contacts Picker API brings that functionality to web applications.
Use cases include selecting contacts to message via an email or chat application, selecting a contacts phone number for use with voice over IP (VOIP), or for discovering contacts who have already joined a social platform. User agents can also offer a consistent experience with other applications on a users device.
When calling the {{domxref('ContactsManager.select', 'select')}} method of the {{domxref('ContactsManager')}} interface, the user is presented with a contact picker, whereby they can then select contact information to share with the web application. User interaction is required before permission to display the contact picker is granted and access to contacts is not persistent; the user must grant access every time a request is made by the application.
This API is only available from a secure top-level browsing context and very carefully considers the sensitivity and privacy of contact data. The onus is on the user for choosing data to share and only allows specific data for selected contacts, with no access to any data for other contacts.
## Interfaces
- {{domxref("ContactAddress")}}
- : Represents a physical address.
- {{domxref("ContactsManager")}}
- : Provides a way for users to select and share limited details of contacts with a web application.
- {{domxref("Navigator.contacts")}}
- : Returns a {{domxref("ContactsManager")}} object instance, from which all other functionality can be accessed.
## Examples
### Feature Detection
The following code checks whether the Contact Picker API is supported.
```js
const supported = "contacts" in navigator;
```
### Checking for Supported Properties
The following asynchronous function uses the `getProperties()` method to check for supported properties.
```js
async function checkProperties() {
const supportedProperties = await navigator.contacts.getProperties();
if (supportedProperties.includes("name")) {
// run code for name support
}
if (supportedProperties.includes("email")) {
// run code for email support
}
if (supportedProperties.includes("tel")) {
// run code for telephone number support
}
if (supportedProperties.includes("address")) {
// run code for address support
}
if (supportedProperties.includes("icon")) {
// run code for avatar support
}
}
```
### Selecting Contacts
The following example sets an array of properties to be retrieved for each contact, as well as setting an options object to allow for multiple contacts to be selected.
An asynchronous function is then defined which uses the `select()` method to present the user with a contact picker interface and handle the chosen results.
```js
const props = ["name", "email", "tel", "address", "icon"];
const opts = { multiple: true };
async function getContacts() {
try {
const contacts = await navigator.contacts.select(props, opts);
handleResults(contacts);
} catch (ex) {
// Handle any errors here.
}
}
```
`handleResults()` is a developer defined function.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [A Contact Picker for the Web](https://developer.chrome.com/docs/capabilities/web-apis/contact-picker)
- [A Contact Picker demo on glitch](https://contact-picker.glitch.me/)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssperspective/index.md | ---
title: CSSPerspective
slug: Web/API/CSSPerspective
page-type: web-api-interface
browser-compat: api.CSSPerspective
---
{{APIRef("CSS Typed Object Model API")}}
The **`CSSPerspective`** interface of the {{domxref('CSS_Object_Model#css_typed_object_model','','',' ')}} represents the [perspective()](/en-US/docs/Web/CSS/transform-function/perspective) value of the individual {{CSSXRef('transform')}} property in CSS. It inherits properties and methods from its parent {{domxref('CSSTransformValue')}}.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CSSPerspective.CSSPerspective", "CSSPerspective()")}}
- : Creates a new `CSSPerspective` object.
## Instance properties
- {{domxref('CSSPerspective.length','length')}}
- : Returns or sets the distance from z=0.
## Examples
To do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssperspective | data/mdn-content/files/en-us/web/api/cssperspective/length/index.md | ---
title: "CSSPerspective: length property"
short-title: length
slug: Web/API/CSSPerspective/length
page-type: web-api-instance-property
browser-compat: api.CSSPerspective.length
---
{{APIRef("CSS Typed OM")}}
The **`length`** property of the
{{domxref("CSSPerspective")}} interface sets the distance from z=0.
It is used to apply a perspective transform to the element and its content. If the
value is 0 or a negative number, no perspective transform is applied.
## Value
A {{domxref("CSSNumericValue")}}
## Examples
To Do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssperspective | data/mdn-content/files/en-us/web/api/cssperspective/cssperspective/index.md | ---
title: "CSSPerspective: CSSPerspective() constructor"
short-title: CSSPerspective()
slug: Web/API/CSSPerspective/CSSPerspective
page-type: web-api-constructor
browser-compat: api.CSSPerspective.CSSPerspective
---
{{APIRef("CSS Typed OM")}}
The **`CSSPerspective()`** constructor creates
a new {{domxref("CSSPerspective")}} object representing the [perspective()](/en-US/docs/Web/CSS/transform-function/perspective) value of
the individual {{CSSXref('transform')}} property in CSS.
## Syntax
```js-nolint
new CSSPerspective(length)
```
### Parameters
- {{domxref('CSSPerspective.length','length')}}
- : A value for the distance from z=0 of the {{domxref('CSSPerspective')}} object to be
constructed. This must be a {{cssxref('length')}}.
### Exceptions
- [`TypeError`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError)
- : Raised if the value of `CSSPerspective.length` exists but is not a
{{cssxref('length')}}.
## Examples
To do
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/atob/index.md | ---
title: atob() global function
short-title: atob()
slug: Web/API/atob
page-type: web-api-global-function
browser-compat: api.atob
---
{{APIRef("HTML DOM")}}{{AvailableInWorkers}}
The **`atob()`** function decodes a
string of data which has been encoded using {{glossary("Base64")}} encoding. You can use
the {{domxref("btoa","btoa()")}} method to encode and transmit
data which may otherwise cause communication problems, then transmit it and use the
`atob()` method to decode the data again. For example, you can encode,
transmit, and decode control characters such as {{Glossary("ASCII")}} values 0 through 31.
For use with arbitrary Unicode strings, see [The "Unicode Problem"](/en-US/docs/Glossary/Base64#the_unicode_problem) section of the {{Glossary("Base64")}} glossary entry.
## Syntax
```js-nolint
atob(encodedData)
```
### Parameters
- `encodedData`
- : A binary string (i.e., a string in which each character in the string is treated as a byte of binary data) containing base64-encoded data.
### Return value
An ASCII string containing decoded data from `encodedData`.
### Exceptions
- `InvalidCharacterError` {{domxref("DOMException")}}
- : Thrown if `encodedData` is not valid base64.
## Examples
```js
const encodedData = btoa("Hello, world"); // encode a string
const decodedData = atob(encodedData); // decode the string
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [A polyfill of `atob`](https://github.com/zloirock/core-js#base64-utility-methods) is available in [`core-js`](https://github.com/zloirock/core-js)
- [`data` URLs](/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs)
- {{domxref("btoa","btoa()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/domimplementation/index.md | ---
title: DOMImplementation
slug: Web/API/DOMImplementation
page-type: web-api-interface
browser-compat: api.DOMImplementation
---
{{ ApiRef("DOM") }}
The **`DOMImplementation`** interface represents an object providing methods which are not dependent on any particular document. Such an object is returned by the {{domxref("Document.implementation")}} property.
## Property
_This interface has no specific property and doesn't inherit any._
## Instance methods
_No inherited method._
- {{domxref("DOMImplementation.createDocument()")}}
- : Creates and returns an {{domxref("XMLDocument")}}.
- {{domxref("DOMImplementation.createDocumentType()")}}
- : Creates and returns a {{domxref("DocumentType")}}.
- {{domxref("DOMImplementation.createHTMLDocument()")}}
- : Creates and returns an HTML {{domxref("Document")}}.
- {{domxref("DOMImplementation.hasFeature()")}} {{Deprecated_Inline}}
- : Returns a boolean value indicating if a given feature is supported or not. This function is unreliable and kept for compatibility purpose alone: except for SVG-related queries, it always returns `true`. Old browsers are very inconsistent in their behavior.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [The DOM interfaces index.](/en-US/docs/Web/API/Document_Object_Model)
| 0 |
data/mdn-content/files/en-us/web/api/domimplementation | data/mdn-content/files/en-us/web/api/domimplementation/hasfeature/index.md | ---
title: "DOMImplementation: hasFeature() method"
short-title: hasFeature()
slug: Web/API/DOMImplementation/hasFeature
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.DOMImplementation.hasFeature
---
{{ApiRef("DOM")}}{{Deprecated_Header}}
The
**`DOMImplementation.hasFeature()`** method returns a
boolean flag indicating if a given feature is supported. It is
deprecated and modern browsers return `true` in all cases.
The different implementations fairly diverged in what kind of features were reported.
The latest version of the spec settled to force this method to always return
`true`, where the functionality was accurate and in use.
## Syntax
```js-nolint
hasFeature(feature, version)
```
### Parameters
- `feature`
- : A string representing the feature name.
- `version`
- : A string representing the version of the specification defining
the feature.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("DOMImplementation")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/domimplementation | data/mdn-content/files/en-us/web/api/domimplementation/createdocument/index.md | ---
title: "DOMImplementation: createDocument() method"
short-title: createDocument()
slug: Web/API/DOMImplementation/createDocument
page-type: web-api-instance-method
browser-compat: api.DOMImplementation.createDocument
---
{{ApiRef("DOM")}}
The **`DOMImplementation.createDocument()`** method creates and
returns an {{domxref("XMLDocument")}}.
## Syntax
```js-nolint
createDocument(namespaceURI, qualifiedNameStr)
createDocument(namespaceURI, qualifiedNameStr, documentType)
```
### Parameters
- `namespaceURI`
- : A string containing the namespace URI of the document to be
created, or `null` if the document doesn't belong to one.
- `qualifiedNameStr`
- : A string containing the qualified name, that is an optional
prefix and colon plus the local root element name, of the document to be created.
- `documentType` {{optional_inline}}
- : Is the {{domxref("DocumentType")}} of the document to be created. It defaults to
`null`.
### Return value
None ({{jsxref("undefined")}}).
## Examples
```js
const doc = document.implementation.createDocument(
"http://www.w3.org/1999/xhtml",
"html",
null,
);
const body = document.createElementNS("http://www.w3.org/1999/xhtml", "body");
body.setAttribute("id", "abc");
doc.documentElement.appendChild(body);
alert(doc.getElementById("abc")); // [object HTMLBodyElement]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("DOMImplementation")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/domimplementation | data/mdn-content/files/en-us/web/api/domimplementation/createdocumenttype/index.md | ---
title: "DOMImplementation: createDocumentType() method"
short-title: createDocumentType()
slug: Web/API/DOMImplementation/createDocumentType
page-type: web-api-instance-method
browser-compat: api.DOMImplementation.createDocumentType
---
{{ ApiRef("DOM")}}
The **`DOMImplementation.createDocumentType()`** method returns
a {{domxref("DocumentType")}} object which can either be used with
{{domxref("DOMImplementation.createDocument")}} upon document creation or can be put
into the document via methods like {{domxref("Node.insertBefore()")}} or
{{domxref("Node.replaceChild()")}}.
## Syntax
```js-nolint
createDocumentType(qualifiedNameStr, publicId, systemId)
```
### Parameters
- `qualifiedNameStr`
- : A string containing the qualified name, like
`svg:svg`.
- `publicId`
- : A string containing the `PUBLIC` identifier.
- `systemId`
- : A string containing the `SYSTEM` identifiers.
### Return value
A [`DocumentType`](/en-US/docs/Web/API/DocumentType).
## Examples
```js
const dt = document.implementation.createDocumentType(
"svg:svg",
"-//W3C//DTD SVG 1.1//EN",
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd",
);
const d = document.implementation.createDocument(
"http://www.w3.org/2000/svg",
"svg:svg",
dt,
);
alert(d.doctype.publicId); // -//W3C//DTD SVG 1.1//EN
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("DOMImplementation")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api/domimplementation | data/mdn-content/files/en-us/web/api/domimplementation/createhtmldocument/index.md | ---
title: "DOMImplementation: createHTMLDocument() method"
short-title: createHTMLDocument()
slug: Web/API/DOMImplementation/createHTMLDocument
page-type: web-api-instance-method
browser-compat: api.DOMImplementation.createHTMLDocument
---
{{ApiRef("DOM")}}
The
**`DOMImplementation.createHTMLDocument()`** method creates a
new HTML {{ domxref("Document") }}.
## Syntax
```js-nolint
createHTMLDocument()
createHTMLDocument(title)
```
### Parameters
- `title` {{optional_inline}}
- : A string containing the title to give the new HTML document.
### Return value
A new HTML {{domxref("Document")}} object.
## Examples
This example creates a new HTML document and inserts it into an {{
HTMLElement("iframe") }} in the current document.
Here's the HTML for this example:
```html
<body>
<p>
Click <a href="javascript:makeDocument()">here</a> to create a new document
and insert it below.
</p>
<iframe id="theFrame" src="about:blank" />
</body>
```
The JavaScript implementation of `makeDocument()` follows:
```js
function makeDocument() {
let frame = document.getElementById("theFrame");
let doc = document.implementation.createHTMLDocument("New Document");
let p = doc.createElement("p");
p.textContent = "This is a new paragraph.";
try {
doc.body.appendChild(p);
} catch (e) {
console.log(e);
}
// Copy the new HTML document into the frame
let destDocument = frame.contentDocument;
let srcNode = doc.documentElement;
let newNode = destDocument.importNode(srcNode, true);
destDocument.replaceChild(newNode, destDocument.documentElement);
}
```
The code in lines 4–12 handle creating the new HTML document and inserting some content
into it. Line 4 uses `createHTMLDocument()` to construct a new HTML document
whose {{ HTMLElement("title") }} is `"New Document"`. Lines 5 and 6 create a
new paragraph element with some simple content, and then lines 8–12 handle inserting the
new paragraph into the new document.
Line 16 pulls the `contentDocument` of the frame; this is the document into
which we'll be injecting the new content. The next two lines handle importing the
contents of our new document into the new document's context. Finally, line 20 actually
replaces the contents of the frame with the new document's contents.
[View Live Examples](https://mdn.dev/archives/media/samples/domref/createHTMLDocument.html)
The returned document is pre-constructed with the following HTML:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>title</title>
</head>
<body>
…
</body>
</html>
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The {{domxref("DOMImplementation")}} interface it belongs to.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlmarqueeelement/index.md | ---
title: HTMLMarqueeElement
slug: Web/API/HTMLMarqueeElement
page-type: web-api-interface
status:
- deprecated
browser-compat: api.HTMLMarqueeElement
---
{{APIRef("HTML DOM")}}{{Deprecated_Header}}
The **`HTMLMarqueeElement`** interface provides methods to manipulate {{HTMLElement("marquee")}} elements.
It inherits properties and methods from the {{DOMxRef("HTMLElement")}} interface.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{DOMxRef("HTMLElement")}}._
- {{DOMxRef("HTMLMarqueeElement.behavior")}} {{Deprecated_Inline}}
- : Sets how the text is scrolled within the marquee. Possible values are `scroll`, `slide` and `alternate`. If no value is specified, the default value is `scroll`.
- {{DOMxRef("HTMLMarqueeElement.bgColor")}} {{Deprecated_Inline}}
- : Sets the background color through color name or hexadecimal value.
- {{DOMxRef("HTMLMarqueeElement.direction")}} {{Deprecated_Inline}}
- : Sets the direction of the scrolling within the marquee. Possible values are `left`, `right`, `up` and `down`. If no value is specified, the default value is `left`.
- {{DOMxRef("HTMLMarqueeElement.height")}} {{Deprecated_Inline}}
- : Sets the height in pixels or percentage value.
- {{DOMxRef("HTMLMarqueeElement.hspace")}} {{Deprecated_Inline}}
- : Sets the horizontal margin.
- {{DOMxRef("HTMLMarqueeElement.loop")}} {{Deprecated_Inline}}
- : Sets the number of times the marquee will scroll. If no value is specified, the default value is −1, which means the marquee will scroll continuously.
- {{DOMxRef("HTMLMarqueeElement.scrollAmount")}} {{Deprecated_Inline}}
- : Sets the amount of scrolling at each interval in pixels. The default value is 6.
- {{DOMxRef("HTMLMarqueeElement.scrollDelay")}} {{Deprecated_Inline}}
- : Sets the interval between each scroll movement in milliseconds. The default value is 85. Note that any value smaller than 60 is ignored and the value 60 is used instead, unless `trueSpeed` is `true`.
- {{DOMxRef("HTMLMarqueeElement.trueSpeed")}} {{Deprecated_Inline}}
- : By default, `scrollDelay` values lower than 60 are ignored. If `trueSpeed` is `true`, then those values are not ignored.
- {{DOMxRef("HTMLMarqueeElement.vspace")}} {{Deprecated_Inline}}
- : Sets the vertical margin.
- {{DOMxRef("HTMLMarqueeElement.width")}} {{Deprecated_Inline}}
- : Sets the width in pixels or percentage value.
## Instance methods
_Inherits methods from its parent, {{DOMxRef("HTMLElement")}}._
- {{DOMxRef("HTMLMarqueeElement.start()")}} {{Deprecated_Inline}}
- : Starts scrolling of the marquee.
- {{DOMxRef("HTMLMarqueeElement.stop()")}} {{Deprecated_Inline}}
- : Stops scrolling of the marquee.
## Events
- {{DOMxRef("HTMLMarqueeElement/bounce_event", "bounce")}} {{Deprecated_Inline}}
- : Fires when the marquee has reached the end of its scroll position. It can only fire when the behavior attribute is set to `alternate`.
- {{DOMxRef("HTMLMarqueeElement/finish_event", "finish")}} {{Deprecated_Inline}}
- : Fires when the marquee has finished the amount of scrolling that is set by the loop attribute. It can only fire when the loop attribute is set to some number that is greater than 0.
- {{DOMxRef("HTMLMarqueeElement/start_event", "start")}} {{Deprecated_Inline}}
- : Fires when the marquee starts scrolling.
## Examples
```html
<marquee>This text will scroll from right to left</marquee>
<marquee direction="up">This text will scroll from bottom to top</marquee>
<marquee
direction="down"
width="250"
height="200"
behavior="alternate"
style="border:solid">
<marquee behavior="alternate">This text will bounce</marquee>
</marquee>
```
{{EmbedLiveSample("Examples", 600, 450)}}
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{HTMLElement("marquee")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/vibration_api/index.md | ---
title: Vibration API
slug: Web/API/Vibration_API
page-type: web-api-overview
browser-compat: api.Navigator.vibrate
---
{{DefaultAPISidebar("Vibration API")}}
Most modern mobile devices include vibration hardware, which lets software code provide physical feedback to the user by causing the device to shake. The **Vibration API** offers Web apps the ability to access this hardware, if it exists, and does nothing if the device doesn't support it.
## Describing vibrations
Vibration is described as a pattern of on-off pulses, which may be of varying lengths. The pattern may consist of either a single integer, describing the number of milliseconds to vibrate, or an array of integers describing a pattern of vibrations and pauses. Vibration is controlled with a single method: {{DOMxRef("Navigator.vibrate()")}}.
### A single vibration
You may pulse the vibration hardware one time by specifying either a single value or an array consisting of only one value:
```js
navigator.vibrate(200);
navigator.vibrate([200]);
```
Both of these examples vibrate the device for 200 ms.
### Vibration patterns
An array of values describes alternating periods in which the device is vibrating and not vibrating. Each value in the array is converted to an integer, then interpreted alternately as the number of milliseconds the device should vibrate and the number of milliseconds it should not be vibrating. For example:
```js
navigator.vibrate([200, 100, 200]);
```
This vibrates the device for 200 ms, then pauses for 100 ms before vibrating the device again for another 200 ms.
You may specify as many vibration/pause pairs as you like, and you may provide either an even or odd number of entries; it's worth noting that you don't have to provide a pause as your last entry since the vibration automatically stops at the end of each vibration period.
### Canceling existing vibrations
Calling {{DOMxRef("Navigator.vibrate()")}} with a value of `0`, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern.
### Continued vibrations
Some basic `setInterval` and `clearInterval` action will allow you to create persistent vibration:
```js
let vibrateInterval;
// Starts vibration at passed in level
function startVibrate(duration) {
navigator.vibrate(duration);
}
// Stops vibration
function stopVibrate() {
// Clear interval and stop persistent vibrating
if (vibrateInterval) clearInterval(vibrateInterval);
navigator.vibrate(0);
}
// Start persistent vibration at given duration and interval
// Assumes a number value is given
function startPersistentVibrate(duration, interval) {
vibrateInterval = setInterval(() => {
startVibrate(duration);
}, interval);
}
```
Of course, the snippet above doesn't take into account the array method of vibration; persistent array-based vibration will require calculating the sum of the array items and creating an interval based on that number (with an additional delay, probably).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{DOMxRef("Navigator.vibrate()")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/gamepadbutton/index.md | ---
title: GamepadButton
slug: Web/API/GamepadButton
page-type: web-api-interface
browser-compat: api.GamepadButton
---
{{APIRef("Gamepad API")}}{{securecontext_header}}
The **`GamepadButton`** interface defines an individual button of a gamepad or other controller, allowing access to the current state of different types of buttons available on the control device.
A `GamepadButton` object is returned by querying any value of the array returned by the `buttons` property of the {{domxref("Gamepad")}} interface.
## Instance properties
- {{domxref("GamepadButton.pressed")}} {{ReadOnlyInline}}
- : A boolean value indicating whether the button is currently pressed (`true`) or unpressed (`false`).
- {{domxref("GamepadButton.touched")}} {{ReadOnlyInline}}
- : A boolean value indicating whether the button is currently touched (`true`) or not touched (`false`).
- {{domxref("GamepadButton.value")}} {{ReadOnlyInline}}
- : A double value used to represent the current state of analog buttons, such as the triggers on many modern gamepads. The values are normalized to the range 0.0 —1.0, with 0.0 representing a button that is not pressed, and 1.0 representing a button that is fully pressed.
## Example
The button values in the following example are stored as an array of {{domxref("GamepadButton")}} objects. This simple example checks to see if the {{domxref("GamepadButton.value")}} of a button is greater than `0`, or if the {{domxref("GamepadButton.pressed")}} property indicates the button has been pressed.
```js
function gameLoop() {
const gp = navigator.getGamepads()[0];
if (gp.buttons[0].value > 0 || gp.buttons[0].pressed) {
b--;
} else if (gp.buttons[1].value > 0 || gp.buttons[1].pressed) {
a++;
} else if (gp.buttons[2].value > 0 || gp.buttons[2].pressed) {
b++;
} else if (gp.buttons[3].value > 0 || gp.buttons[3].pressed) {
a--;
}
ball.style.left = `${a * 2}px`; // ball is a UI widget
ball.style.top = `${b * 2}px`;
requestAnimationFrame(gameLoop);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
[Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadbutton | data/mdn-content/files/en-us/web/api/gamepadbutton/touched/index.md | ---
title: "GamepadButton: touched property"
short-title: touched
slug: Web/API/GamepadButton/touched
page-type: web-api-instance-property
browser-compat: api.GamepadButton.touched
---
{{APIRef("Gamepad API")}}{{SecureContext_Header}}
The **`touched`** property of the
{{domxref("GamepadButton")}} interface returns a `boolean` indicating whether
a button capable of detecting touch is currently touched (`true`) or not touched (`false`).
If the button is not capable of detecting touch but can return an analog value, the property will be `true` if the value is greater than `0`, and `false` otherwise. If the button is not capable of detecting touch and can only report a digital value, then it should mirror the {{domxref("GamepadButton.pressed")}} property.
## Value
A {{jsxref("Boolean")}}. True if touched.
## Examples
```js
let gp = navigator.getGamepads()[0]; // Get the first gamepad object
if (gp.buttons[0].touched) {
// respond to button being touched
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadbutton | data/mdn-content/files/en-us/web/api/gamepadbutton/value/index.md | ---
title: "GamepadButton: value property"
short-title: value
slug: Web/API/GamepadButton/value
page-type: web-api-instance-property
browser-compat: api.GamepadButton.value
---
{{APIRef("Gamepad API")}}{{SecureContext_Header}}
The **`GamepadButton.value`** property of the
{{domxref("GamepadButton")}} interface returns a double value used to represent the
current state of analog buttons on many modern gamepads, such as the triggers.
The values are normalized to the range `0.0` — `1.0`, with
`0.0` representing a button that is not pressed, and 1.0 representing a
button that is fully pressed.
## Examples
```js
let gp = navigator.getGamepads()[0];
if (gp.buttons[0].value > 0) {
// respond to analog button being pressed in
}
```
## Value
A double.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
[Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api/gamepadbutton | data/mdn-content/files/en-us/web/api/gamepadbutton/pressed/index.md | ---
title: "GamepadButton: pressed property"
short-title: pressed
slug: Web/API/GamepadButton/pressed
page-type: web-api-instance-property
browser-compat: api.GamepadButton.pressed
---
{{APIRef("Gamepad API")}}{{SecureContext_Header}}
The **`GamepadButton.pressed`** property of the
{{domxref("GamepadButton")}} interface returns a `boolean` indicating whether
the button is currently pressed (`true`) or unpressed (`false`).
## Examples
```js
let gp = navigator.getGamepads()[0]; // Get the first gamepad object
if (gp.buttons[0].pressed) {
// respond to button being pressed
}
```
## Value
A boolean value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using the Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgsymbolelement/index.md | ---
title: SVGSymbolElement
slug: Web/API/SVGSymbolElement
page-type: web-api-interface
browser-compat: api.SVGSymbolElement
---
{{APIRef("SVG")}}
The **`SVGSymbolElement`** interface corresponds to the {{SVGElement("symbol")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface doesn't implement any specific properties, but inherits properties from its parent interface, {{domxref("SVGGraphicsElement")}}._
## Instance methods
_This interface doesn't implement any specific methods, but inherits methods from its parent interface, {{domxref("SVGGraphicsElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/mediastreamtrackprocessor/index.md | ---
title: MediaStreamTrackProcessor
slug: Web/API/MediaStreamTrackProcessor
page-type: web-api-interface
status:
- experimental
browser-compat: api.MediaStreamTrackProcessor
---
{{APIRef("Insertable Streams for MediaStreamTrack API")}}{{SeeCompatTable}}
The **`MediaStreamTrackProcessor`** interface of the {{domxref('Insertable Streams for MediaStreamTrack API')}} consumes a {{domxref("MediaStreamTrack")}} object's source and generates a stream of media frames.
## Constructor
- {{domxref("MediaStreamTrackProcessor.MediaStreamTrackProcessor", "MediaStreamTrackProcessor()")}} {{Experimental_Inline}}
- : Creates a new `MediaStreamTrackProcessor` object.
## Instance properties
- {{domxref("MediaStreamTrackProcessor.readable")}} {{Experimental_Inline}}
- : Returns a {{domxref("ReadableStream")}}.
## Examples
The following example is from the article [Insertable streams for MediaStreamTrack](https://developer.chrome.com/docs/capabilities/web-apis/mediastreamtrack-insertable-media-processing), and demonstrates a barcode scanner application, which transforms the stream accessed via {{domxref("MediaStreamTrackProcessor.readable")}} by highlighting the barcode.
```js
const stream = await getUserMedia({ video: true });
const videoTrack = stream.getVideoTracks()[0];
const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });
const transformer = new TransformStream({
async transform(videoFrame, controller) {
const barcodes = await detectBarcodes(videoFrame);
const newFrame = highlightBarcodes(videoFrame, barcodes);
videoFrame.close();
controller.enqueue(newFrame);
},
});
trackProcessor.readable
.pipeThrough(transformer)
.pipeTo(trackGenerator.writable);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrackprocessor | data/mdn-content/files/en-us/web/api/mediastreamtrackprocessor/readable/index.md | ---
title: "MediaStreamTrackProcessor: readable property"
short-title: readable
slug: Web/API/MediaStreamTrackProcessor/readable
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.MediaStreamTrackProcessor.readable
---
{{APIRef("Insertable Streams for MediaStreamTrack API")}}{{SeeCompatTable}}
The **`readable`** property of the {{domxref("MediaStreamTrackProcessor")}} interface returns a {{domxref("ReadableStream")}}.
## Value
A {{domxref("ReadableStream")}}.
## Examples
In the following example video frames from the {{domxref("ReadableStream")}} are transformed.
```js
const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
const trackGenerator = new MediaStreamTrackGenerator({ kind: "video" });
/* */
trackProcessor.readable
.pipeThrough(transformer)
.pipeTo(trackGenerator.writable);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/mediastreamtrackprocessor | data/mdn-content/files/en-us/web/api/mediastreamtrackprocessor/mediastreamtrackprocessor/index.md | ---
title: "MediaStreamTrackProcessor: MediaStreamTrackProcessor() constructor"
short-title: MediaStreamTrackProcessor()
slug: Web/API/MediaStreamTrackProcessor/MediaStreamTrackProcessor
page-type: web-api-constructor
status:
- experimental
browser-compat: api.MediaStreamTrackProcessor.MediaStreamTrackProcessor
---
{{APIRef("Insertable Streams for MediaStreamTrack API")}}{{SeeCompatTable}}
The **`MediaStreamTrackProcessor()`** constructor creates a new {{domxref("MediaStreamTrackProcessor")}} object which consumes a {{domxref("MediaStreamTrack")}} object's source and generates a stream of media frames.
## Syntax
```js-nolint
new MediaStreamTrackProcessor(options)
```
### Parameters
- `options`
- : An object with the following properties:
- `track`
- : A {{domxref("MediaStreamTrack")}}.
- `maxBufferSize` {{optional_inline}}
- : An integer specifying the maximum number of media frames to be buffered.
## Examples
In the following example a new `MediaStreamTrackProcessor` is created.
```js
const trackProcessor = new MediaStreamTrackProcessor({ track: videoTrack });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/htmlparamelement/index.md | ---
title: HTMLParamElement
slug: Web/API/HTMLParamElement
page-type: web-api-interface
status:
- deprecated
browser-compat: api.HTMLParamElement
---
{{APIRef("HTML DOM")}}{{Deprecated_Header}}
The **`HTMLParamElement`** interface provides special properties (beyond those of the regular {{domxref("HTMLElement")}} object interface it inherits) for manipulating {{HTMLElement("param")}} elements, representing a pair of a key and a value that acts as a parameter for an {{HTMLElement("object")}} element.
{{InheritanceDiagram}}
## Instance properties
_Inherits properties from its parent, {{domxref("HTMLElement")}}._
- {{domxref("HTMLParamElement.name")}} {{Deprecated_Inline}}
- : A string representing the name of the parameter. It reflects the [`name`](/en-US/docs/Web/HTML/Element/param#name) attribute.
- {{domxref("HTMLParamElement.value")}} {{Deprecated_Inline}}
- : A string representing the value associated to the parameter. It reflects the [`value`](/en-US/docs/Web/HTML/Element/param#value) attribute.
- {{domxref("HTMLParamElement.type")}} {{Deprecated_Inline}}
- : A string containing the type of the parameter when `valueType` has the `"ref"` value. It reflects the [`type`](/en-US/docs/Web/HTML/Element/param#type) attribute.
- {{domxref("HTMLParamElement.valueType")}} {{Deprecated_Inline}}
- : A string containing the type of the `value`. It reflects the [valuetype](/en-US/docs/Web/HTML/Element/param#valuetype) attribute and has one of the values: `"data"`, `"ref"`, or `"object"`.
## Instance methods
_No specific methods, inherits methods from its parent, {{domxref("HTMLElement")}}._
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- The HTML element implementing this interface: {{ HTMLElement("param") }}.
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/largestcontentfulpaint/index.md | ---
title: LargestContentfulPaint
slug: Web/API/LargestContentfulPaint
page-type: web-api-interface
browser-compat: api.LargestContentfulPaint
---
{{APIRef("Performance API")}}
The `LargestContentfulPaint` interface provides timing information about the largest image or text paint before user input on a web page.
## Description
The key moment this API provides is the {{Glossary("Largest Contentful Paint")}} (LCP) metric. It provides the render time of the largest image or text block visible within the viewport, recorded from when the page first begins to load. The following elements are considered when determining the LCP:
- {{HTMLElement("img")}} elements.
- [`<image>`](/en-US/docs/Web/SVG/Element/image) elements inside an SVG.
- The poster images of {{HTMLElement("video")}} elements.
- Elements with a {{cssxref("background-image")}}.
- Groups of text nodes, such as {{HTMLElement("p")}}.
To measure render times of other elements, use the {{domxref("PerformanceElementTiming")}} API.
Additional key paint moments are provided by the {{domxref("PerformancePaintTiming")}} API:
- {{Glossary("First paint")}} (FP): Time when anything is rendered. Note that the marking of the first paint is optional, not all user agents report it.
- {{Glossary("First contentful paint")}} (FCP): Time when the first bit of DOM text or image content is rendered.
`LargestContentfulPaint` inherits from {{domxref("PerformanceEntry")}}.
{{InheritanceDiagram}}
## Instance properties
This interface extends the following {{domxref("PerformanceEntry")}} properties by qualifying and constraining the properties as follows:
- {{domxref("PerformanceEntry.entryType")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns "`largest-contentful-paint`".
- {{domxref("PerformanceEntry.name")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Always returns an empty string.
- {{domxref("PerformanceEntry.startTime")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the value of this entry's {{domxref("LargestContentfulPaint.renderTime", "renderTime")}} if it is not `0`, otherwise the value of this entry's {{domxref("LargestContentfulPaint.loadTime", "loadTime")}}.
- {{domxref("PerformanceEntry.duration")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns `0`, as `duration` is not applicable to this interface.
It also supports the following properties:
- {{domxref("LargestContentfulPaint.element")}} {{ReadOnlyInline}}
- : The element that is the current largest contentful paint.
- {{domxref("LargestContentfulPaint.renderTime")}} {{ReadOnlyInline}}
- : The time the element was rendered to the screen. May not be available if the element is a cross-origin image loaded without the `Timing-Allow-Origin` header.
- {{domxref("LargestContentfulPaint.loadTime")}} {{ReadOnlyInline}}
- : The time the element was loaded.
- {{domxref("LargestContentfulPaint.size")}} {{ReadOnlyInline}}
- : The intrinsic size of the element returned as the area (width \* height).
- {{domxref("LargestContentfulPaint.id")}} {{ReadOnlyInline}}
- : The id of the element. This property returns an empty string when there is no id.
- {{domxref("LargestContentfulPaint.url")}} {{ReadOnlyInline}}
- : If the element is an image, the request url of the image.
## Instance methods
_This interface also inherits methods from {{domxref("PerformanceEntry")}}._
- {{domxref("LargestContentfulPaint.toJSON()")}}
- : Returns a JSON representation of the `LargestContentfulPaint` object.
## Examples
### Observing the largest contentful paint
In the following example, an observer is registered to get the largest contentful paint while the page is loading. The `buffered` flag is used to access data from before observer creation.
The LCP API analyzes all content it finds (including content that is removed from the DOM). When new largest content is found, it creates a new entry. It stops searching for larger content when scroll or input events occur, since these events likely introduce new content on the website. Thus the LCP is the last performance entry reported by the observer.
```js
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1]; // Use the latest LCP candidate
console.log("LCP:", lastEntry.startTime);
console.log(lastEntry);
});
observer.observe({ type: "largest-contentful-paint", buffered: true });
```
### Cross-origin image render time
For security reasons, the value of the {{domxref("LargestContentfulPaint.renderTime", "renderTime")}} property is `0` if the resource is a cross-origin request. Instead the {{domxref("LargestContentfulPaint.loadTime", "loadTime")}} is exposed. To expose cross-origin render time information, the {{HTTPHeader("Timing-Allow-Origin")}} HTTP response header needs to be set.
For example, to allow `https://developer.mozilla.org` to see `renderTime`, the cross-origin resource should send:
```http
Timing-Allow-Origin: https://developer.mozilla.org
```
Like in the code example, you can use {{domxref("PerformanceEntry.startTime", "startTime")}}, which returns the value of the entry's {{domxref("LargestContentfulPaint.renderTime", "renderTime")}} if it is not `0`, and otherwise the value of this entry's {{domxref("LargestContentfulPaint.loadTime", "loadTime")}}. However, it is recommended to set the {{HTTPHeader("Timing-Allow-Origin")}} header so that the metrics will be more accurate.
If you use `startTime`, you can flag any inaccuracies by checking if `renderTime` was used:
```js
const isAccurateLCP = entry.renderTime ? true : false;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{Glossary("Largest Contentful Paint")}}
- {{Glossary("First contentful paint")}}
- {{Glossary("First paint")}}
| 0 |
data/mdn-content/files/en-us/web/api/largestcontentfulpaint | data/mdn-content/files/en-us/web/api/largestcontentfulpaint/element/index.md | ---
title: "LargestContentfulPaint: element property"
short-title: element
slug: Web/API/LargestContentfulPaint/element
page-type: web-api-instance-property
browser-compat: api.LargestContentfulPaint.element
---
{{APIRef("Performance API")}}
The **`element`** read-only property of the {{domxref("LargestContentfulPaint")}} interface returns an object representing the {{domxref("Element")}} that is the largest contentful paint.
## Value
An {{domxref("Element")}}.
## Examples
### Logging the largest contentful paint element
This example uses a {{domxref("PerformanceObserver")}} notifying of new `largest-contentful-paint` performance entries as they are recorded in the browser's performance timeline. The `buffered` option is used to access entries from before the observer creation.
```js
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1]; // Use the latest LCP candidate
console.log(lastEntry.element);
});
observer.observe({ type: "largest-contentful-paint", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/largestcontentfulpaint | data/mdn-content/files/en-us/web/api/largestcontentfulpaint/rendertime/index.md | ---
title: "LargestContentfulPaint: renderTime property"
short-title: renderTime
slug: Web/API/LargestContentfulPaint/renderTime
page-type: web-api-instance-property
browser-compat: api.LargestContentfulPaint.renderTime
---
{{APIRef("Performance API")}}
The **`renderTime`** read-only property of the {{domxref("LargestContentfulPaint")}} interface represents the time that the element was rendered to the screen.
## Value
The `renderTime` property can have the following values:
- A {{domxref("DOMHighResTimeStamp","timestamp")}} representing the time in milliseconds that the element was rendered to the screen.
- `0` if the resource is a cross-origin request and no {{HTTPHeader("Timing-Allow-Origin")}} HTTP response header is used.
## Examples
### Logging the renderTime of the largest contentful paint
This example uses a {{domxref("PerformanceObserver")}} notifying of new `largest-contentful-paint` performance entries as they are recorded in the browser's performance timeline. The `buffered` option is used to access entries from before the observer creation.
```js
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1]; // Use the latest LCP candidate
console.log(lastEntry.renderTime);
});
observer.observe({ type: "largest-contentful-paint", buffered: true });
```
### Cross-origin image render time
For security reasons, the value of the {{domxref("LargestContentfulPaint.renderTime", "renderTime")}} property is `0` if the resource is a cross-origin request. Instead the {{domxref("LargestContentfulPaint.loadTime", "loadTime")}} is exposed. To expose cross-origin render time information, the {{HTTPHeader("Timing-Allow-Origin")}} HTTP response header needs to be set.
For example, to allow `https://developer.mozilla.org` to see `renderTime`, the cross-origin resource should send:
```http
Timing-Allow-Origin: https://developer.mozilla.org
```
Alternatively, you can use {{domxref("PerformanceEntry.startTime", "startTime")}} which returns the value of the entry's {{domxref("LargestContentfulPaint.renderTime", "renderTime")}} if it is not `0`, and otherwise the value of this entry's {{domxref("LargestContentfulPaint.loadTime", "loadTime")}}. However, it is recommended to set the {{HTTPHeader("Timing-Allow-Origin")}} header so that the metrics will be more accurate.
If you use `startTime`, you can flag any inaccuracies by checking if `renderTime` was used:
```js
const isAccurateLCP = entry.renderTime ? true : false;
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/largestcontentfulpaint | data/mdn-content/files/en-us/web/api/largestcontentfulpaint/loadtime/index.md | ---
title: "LargestContentfulPaint: loadTime property"
short-title: loadTime
slug: Web/API/LargestContentfulPaint/loadTime
page-type: web-api-instance-property
browser-compat: api.LargestContentfulPaint.loadTime
---
{{APIRef("Performance API")}}
The **`loadTime`** read-only property of the {{domxref("LargestContentfulPaint")}} interface returns the time that the element was loaded.
## Value
A {{domxref("DOMHighResTimeStamp","timestamp")}} representing the time in milliseconds that the element was loaded.
## Examples
### Logging the loadTime of the largest contentful paint
This example uses a {{domxref("PerformanceObserver")}} notifying of new `largest-contentful-paint` performance entries as they are recorded in the browser's performance timeline. The `buffered` option is used to access entries from before the observer creation.
```js
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1]; // Use the latest LCP candidate
console.log(lastEntry.loadTime);
});
observer.observe({ type: "largest-contentful-paint", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/largestcontentfulpaint | data/mdn-content/files/en-us/web/api/largestcontentfulpaint/url/index.md | ---
title: "LargestContentfulPaint: url property"
short-title: url
slug: Web/API/LargestContentfulPaint/url
page-type: web-api-instance-property
browser-compat: api.LargestContentfulPaint.url
---
{{APIRef("Performance API")}}
The **`url`** read-only property of the {{domxref("LargestContentfulPaint")}} interface returns the request URL of the element, if the element is an image.
## Value
A string containing a URL.
## Examples
### Logging the url of the largest contentful paint
This example uses a {{domxref("PerformanceObserver")}} notifying of new `largest-contentful-paint` performance entries as they are recorded in the browser's performance timeline. The `buffered` option is used to access entries from before the observer creation.
```js
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1]; // Use the latest LCP candidate
console.log(lastEntry.url);
});
observer.observe({ type: "largest-contentful-paint", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/largestcontentfulpaint | data/mdn-content/files/en-us/web/api/largestcontentfulpaint/size/index.md | ---
title: "LargestContentfulPaint: size property"
short-title: size
slug: Web/API/LargestContentfulPaint/size
page-type: web-api-instance-property
browser-compat: api.LargestContentfulPaint.size
---
{{APIRef("Performance API")}}
The **`size`** read-only property of the {{domxref("LargestContentfulPaint")}} interface returns the intrinsic size of the element that is the largest contentful paint.
The `size` of the element is the `width` times `height` of the {{domxref("DOMRectReadOnly","rectangle")}} that this element creates on the screen.
## Value
An integer representing the width times height of the element.
## Examples
### Logging the size of the largest contentful paint element
This example uses a {{domxref("PerformanceObserver")}} notifying of new `largest-contentful-paint` performance entries as they are recorded in the browser's performance timeline. The `buffered` option is used to access entries from before the observer creation.
```js
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1]; // Use the latest LCP candidate
console.log(lastEntry.size);
});
observer.observe({ type: "largest-contentful-paint", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/largestcontentfulpaint | data/mdn-content/files/en-us/web/api/largestcontentfulpaint/id/index.md | ---
title: "LargestContentfulPaint: id property"
short-title: id
slug: Web/API/LargestContentfulPaint/id
page-type: web-api-instance-property
browser-compat: api.LargestContentfulPaint.id
---
{{APIRef("Performance API")}}
The **`id`** read-only property of the {{domxref("LargestContentfulPaint")}} interface returns the ID of the element that is the largest contentful paint.
## Value
A string containing the ID of the element, or the empty string if there is no such ID.
## Examples
### Logging the largest contentful paint element ID
This example uses a {{domxref("PerformanceObserver")}} notifying of new `largest-contentful-paint` performance entries as they are recorded in the browser's performance timeline. The `buffered` option is used to access entries from before the observer creation.
```js
const observer = new PerformanceObserver((list) => {
const entries = list.getEntries();
const lastEntry = entries[entries.length - 1]; // Use the latest LCP candidate
console.log(lastEntry.id);
});
observer.observe({ type: "largest-contentful-paint", buffered: true });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/largestcontentfulpaint | data/mdn-content/files/en-us/web/api/largestcontentfulpaint/tojson/index.md | ---
title: "LargestContentfulPaint: toJSON() method"
short-title: toJSON()
slug: Web/API/LargestContentfulPaint/toJSON
page-type: web-api-instance-method
browser-compat: api.LargestContentfulPaint.toJSON
---
{{APIRef("Performance API")}}
The **`toJSON()`** method of the {{domxref("LargestContentfulPaint")}} interface is a {{Glossary("Serialization","serializer")}}; it returns a JSON representation of the {{domxref("LargestContentfulPaint")}} object.
## Syntax
```js-nolint
toJSON()
```
### Parameters
None.
### Return value
A {{jsxref("JSON")}} object that is the serialization of the {{domxref("LargestContentfulPaint")}} object.
The JSON doesn't contain the {{domxref("LargestContentfulPaint.element", "element")}} property because it is of type {{domxref("Element")}}, which doesn't provide a `toJSON()` operation.
## Examples
### Using the toJSON method
In this example, calling `entry.toJSON()` returns a JSON representation of the `LargestContentfulPaint` object.
```js
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach((entry) => {
console.log(entry.toJSON());
});
});
observer.observe({ type: "largest-contentful-paint", buffered: true });
```
This would log a JSON object like so:
```json
{
"name": "",
"entryType": "largest-contentful-paint",
"startTime": 468.2,
"duration": 0,
"size": 19824,
"renderTime": 468.2,
"loadTime": 0,
"id": "",
"url": ""
}
```
To get a JSON string, you can use [`JSON.stringify(entry)`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) directly; it will call `toJSON()` automatically.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("JSON")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/inputdevicecapabilities_api/index.md | ---
title: InputDeviceCapabilities API
slug: Web/API/InputDeviceCapabilities_API
page-type: web-api-overview
status:
- experimental
browser-compat: api.InputDeviceCapabilities
---
{{DefaultAPISidebar("Input Device Capabilities API")}}{{SeeCompatTable}}
The InputDeviceCapabilities API provides details about the underlying sources of input events. The API attempts to describe how the device behaves rather than what it is. For example, the first version of the API indicates whether a device fires touch events rather than whether it is a touch screen.
## Input device capabilities concepts and usage
Because DOM events abstract device input, they provide no way to learn what device or type of device fired an event. This can lead to instances where the same action triggers multiple event handlers. To deal with this, developers make assumptions and use heuristics to normalize behavior on web pages.
The InputDeviceCapabilities API addresses this problem by abstracting the capabilities of input devices. For example, let's say we have a web page that implements both a `touchstart` and a `mousedown` event. We can assume that if the touchstart event is triggered that the user's device has a touch interface. What about when the mousedown event is triggered? It would be useful to know if a `touchstart` event were also triggered so that we don't take the same action twice. We can do this by checking the sourceCapabilities property of the {{domxref("UIEvent")}}.
```js
myButton.addEventListener("mousedown", (e) => {
// Touch event case handled above, don't change the style again on tap.
if (!e.sourceCapabilities.firesTouchEvents) myButton.classList.add("pressed");
});
```
## Interfaces
- {{domxref("InputDeviceCapabilities")}} {{Experimental_Inline}}
- : Provides logical information about an input device.
## Extensions to other interfaces
- {{domxref("UIEvent.sourceCapabilities")}} {{Experimental_Inline}} {{ReadOnlyInline}}
- : Returns an instance of the `InputDeviceCapabilities` interface, which provides information about the physical device responsible for generating a touch event.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/compositionevent/index.md | ---
title: CompositionEvent
slug: Web/API/CompositionEvent
page-type: web-api-interface
browser-compat: api.CompositionEvent
---
{{APIRef("UI Events")}}
The DOM **`CompositionEvent`** represents events that occur due to the user indirectly entering text.
{{InheritanceDiagram}}
## Constructor
- {{domxref("CompositionEvent.CompositionEvent()", "CompositionEvent()")}}
- : Creates a new `CompositionEvent` object instance.
## Instance properties
_This interface also inherits properties of its parent, {{domxref("UIEvent")}}, and its ancestor — {{domxref("Event")}}._
- {{domxref("CompositionEvent.data")}} {{ReadOnlyInline}}
- : Returns the characters generated by the input method that raised the event; its varies depending on the type of event that generated the `CompositionEvent` object.
- {{domxref("CompositionEvent.locale")}} {{ReadOnlyInline}} {{deprecated_inline}} {{Non-standard_Inline}}
- : Returns the locale of current input method (for example, the keyboard layout locale if the composition is associated with {{glossary("IME")}}).
## Instance methods
_This interface also inherits methods of its parent, {{domxref("UIEvent")}}, and its ancestor — {{domxref("Event")}}._
- {{domxref("CompositionEvent.initCompositionEvent()")}} {{deprecated_inline}}
- : Initializes the attributes of a `CompositionEvent` object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [compositionstart](/en-US/docs/Web/API/Element/compositionstart_event)
- [compositionend](/en-US/docs/Web/API/Element/compositionend_event)
- [compositionupdate](/en-US/docs/Web/API/Element/compositionupdate_event)
- [UIEvent](/en-US/docs/Web/API/UIEvent)
- [Event](/en-US/docs/Web/API/Event)
| 0 |
data/mdn-content/files/en-us/web/api/compositionevent | data/mdn-content/files/en-us/web/api/compositionevent/data/index.md | ---
title: "CompositionEvent: data property"
short-title: data
slug: Web/API/CompositionEvent/data
page-type: web-api-instance-property
browser-compat: api.CompositionEvent.data
---
{{APIRef("UI Events")}}
The **`data`** read-only property of the
{{domxref("CompositionEvent")}} interface returns the characters generated by the input
method that raised the event; its exact nature varies depending on the type of event
that generated the `CompositionEvent` object.
## Value
A string representing the event data:
- For `compositionstart` events, this is the currently selected text that
will be replaced by the string being composed. This value doesn't change even if
content changes the selection range; rather, it indicates the string that was selected
when composition started.
- For `compositionupdate`, this is the string as it stands currently as
editing is ongoing.
- For `compositionend` events, this is the string as committed to the
editor.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CompositionEvent")}}
| 0 |
data/mdn-content/files/en-us/web/api/compositionevent | data/mdn-content/files/en-us/web/api/compositionevent/compositionevent/index.md | ---
title: "CompositionEvent: CompositionEvent() constructor"
short-title: CompositionEvent()
slug: Web/API/CompositionEvent/CompositionEvent
page-type: web-api-constructor
browser-compat: api.CompositionEvent.CompositionEvent
---
{{APIRef("UI Events")}}
The **`CompositionEvent()`** constructor creates a new {{domxref("CompositionEvent")}} object.
## Syntax
```js-nolint
new CompositionEvent(type)
new CompositionEvent(type, options)
```
### Parameters
- `type`
- : A string with the name of the event.
It is case-sensitive and browsers set it to `compositionstart`, `compositionupdate`, or `compositionend`.
- `options` {{optional_inline}}
- : An object that, _in addition of the properties defined in {{domxref("UIEvent/UIEvent", "UIEvent()")}}_, has the following properties:
- `data` {{optional_inline}}
- : A string used to initialize the {{domxref("CompositionEvent.data", "data")}} property of the new
{{domxref("CompositionEvent")}}. Browser-generated events set it to the characters generated by the IME
composition.
### Return value
A new {{domxref("CompositionEvent")}} object.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CompositionEvent")}}, the interface of the objects it constructs.
| 0 |
data/mdn-content/files/en-us/web/api/compositionevent | data/mdn-content/files/en-us/web/api/compositionevent/locale/index.md | ---
title: "CompositionEvent: locale property"
short-title: locale
slug: Web/API/CompositionEvent/locale
page-type: web-api-instance-property
status:
- deprecated
- non-standard
browser-compat: api.CompositionEvent.locale
---
{{deprecated_header}}{{APIRef("UI Events")}}{{Non-standard_header}}
The **`locale`** read-only property of the
{{domxref("CompositionEvent")}} interface returns the locale of current input method
(for example, the keyboard layout locale if the composition is associated with {{glossary("IME")}}).
> **Warning:** Even for browsers supporting it, don't trust the value contained in this property.
> Even if technically it is accessible, the way to set it up when creating a {{domxref("CompositionEvent")}}
> is not guaranteed to be coherent.
## Value
A string representing the locale of current input method.
## Specifications
This property was in early versions of different specifications. It is now only kept for compatibility purposes, and the way
to set its value when creating a {{domxref("CompositionEvent")}} is [not well defined](https://github.com/w3c/uievents/issues/48).
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CompositionEvent")}}
| 0 |
data/mdn-content/files/en-us/web/api/compositionevent | data/mdn-content/files/en-us/web/api/compositionevent/initcompositionevent/index.md | ---
title: "CompositionEvent: initCompositionEvent() method"
short-title: initCompositionEvent()
slug: Web/API/CompositionEvent/initCompositionEvent
page-type: web-api-instance-method
status:
- deprecated
browser-compat: api.CompositionEvent.initCompositionEvent
---
{{deprecated_header}}{{APIRef("UI Events")}}
The **`initCompositionEvent()`**
method of the {{domxref("CompositionEvent")}} interface initializes the attributes of a
`CompositionEvent` object instance.
> **Note:** The correct way of creating a {{domxref("CompositionEvent")}} is to use
> the constructor {{domxref("CompositionEvent.CompositionEvent", "CompositionEvent()")}}.
## Syntax
```js-nolint
initCompositionEvent(type, canBubble, cancelable, view, data, locale)
```
### Parameters
- `type`
- : A string representing the type of composition event; this will be
one of `compositionstart`, `compositionupdate`, or
`compositionend`.
- `canBubble`
- : A boolean value specifying whether or not the event can bubble.
- `cancelable`
- : A boolean value indicating whether or not the event can be canceled.
- `view`
- : The {{domxref("Window")}} object from which the event was generated.
- `data`
- : A string representing the value of the `data`
attribute.
- `locale`
- : A string representing the value of the `locale`
attribute.
### Return value
None ({{jsxref("undefined")}}).
## Specifications
This method is no longer on a standardization track. It is kept for compatibility purposes. Use the constructor {{domxref("CompositionEvent.CompositionEvent", "CompositionEvent()")}}.
## Browser compatibility
{{Compat}}
## See also
- {{domxref("CompositionEvent")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/svgfetileelement/index.md | ---
title: SVGFETileElement
slug: Web/API/SVGFETileElement
page-type: web-api-interface
browser-compat: api.SVGFETileElement
---
{{APIRef("SVG")}}
The **`SVGFETileElement`** interface corresponds to the {{SVGElement("feTile")}} element.
{{InheritanceDiagram}}
## Instance properties
_This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._
- {{domxref("SVGFETileElement.height")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element.
- {{domxref("SVGFETileElement.in1")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("in")}} attribute of the given element.
- {{domxref("SVGFETileElement.result")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element.
- {{domxref("SVGFETileElement.width")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element.
- {{domxref("SVGFETileElement.x")}} {{ReadOnlyInline}}
- : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element.
- {{domxref("SVGFETileElement.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("feTile")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/remoteplayback/index.md | ---
title: RemotePlayback
slug: Web/API/RemotePlayback
page-type: web-api-interface
browser-compat: api.RemotePlayback
---
{{APIRef("Remote Playback API")}}
The **`RemotePlayback`** interface of the {{domxref('Remote Playback API','','',' ')}} allows the page to detect availability of remote playback devices, then connect to and control playing on these devices.
{{InheritanceDiagram}}
## Instance properties
- {{domxref("RemotePlayback.state")}} {{ReadOnlyInline}}
- : Represents the `RemotePlayback` connection's state. One of:
- `"connecting"`
- : The user agent is attempting to initiate remote playback with the selected device.
- `"connected"`
- : The transition from local to remote playback has happened, all commands will now take place on the remote device.
- `"disconnected"`
- : The remote playback has not been initiated, has failed to initiate, or has been stopped.
## Instance methods
- {{domxref("RemotePlayback.watchAvailability()")}}
- : A {{jsxref("Promise")}} that resolves with a `callbackId` of an available remote playback device.
- {{domxref("RemotePlayback.cancelWatchAvailability()")}}
- : Cancels the request to monitor the availability of remote playback devices.
- {{domxref("RemotePlayback.prompt()")}}
- : Prompts the user to select and give permission to connect to a remote playback device.
## Events
- {{domxref("RemotePlayback.connecting_event", "connecting")}}
- : Fired when the user agent initiates remote playback.
- {{domxref("RemotePlayback.connect_event", "connect")}}
- : Fired when the user agent successfully connects to the remote device.
- {{domxref("RemotePlayback.disconnect_event", "disconnect")}}
- : Fired when the user agent disconnects from the remote device.
## Examples
The following example demonstrates a player with custom controls that support remote playback. Initially the button used to select a device is hidden:
```html
<video id="videoElement" src="https://example.org/media.ext">
<button id="deviceBtn" style="display: none;">Pick device</button>
</video>
```
The {{domxref("RemotePlayback.watchAvailability()")}} method is used to watch for available remote playback devices. If a device is available, use the callback to show the button.
```js
const deviceBtn = document.getElementById("deviceBtn");
const videoElem = document.getElementById("videoElement");
function availabilityCallback(available) {
// Show or hide the device picker button depending on device availability.
deviceBtn.style.display = available ? "inline" : "none";
}
videoElem.remote.watchAvailability(availabilityCallback).catch(() => {
/* If the device cannot continuously watch available,
show the button to allow the user to try to prompt for a connection.*/
deviceBtn.style.display = "inline";
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/remoteplayback | data/mdn-content/files/en-us/web/api/remoteplayback/disconnect_event/index.md | ---
title: "RemotePlayback: disconnect event"
short-title: disconnect
slug: Web/API/RemotePlayback/disconnect_event
page-type: web-api-event
browser-compat: api.RemotePlayback.disconnect_event
---
{{APIRef("Remote Playback API")}}
The **`disconnect`** event of the {{domxref("RemotePlayback")}} interface fires when the user agent disconnects from the remote device.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("disconnect", (event) => {});
ondisconnect = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Example
In the following example the value of {{domxref("RemotePlayback.state")}} is printed to the console when the user agent disconnects from the remote device.
```js
RemotePlayback.disconnect = () => {
console.log(RemotePlayback.state);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/remoteplayback | data/mdn-content/files/en-us/web/api/remoteplayback/prompt/index.md | ---
title: "RemotePlayback: prompt() method"
short-title: prompt()
slug: Web/API/RemotePlayback/prompt
page-type: web-api-instance-method
browser-compat: api.RemotePlayback.prompt
---
{{APIRef("Remote Playback API")}}
The **`prompt()`** method of the {{domxref("RemotePlayback")}} interface prompts the user to select an available remote playback device and give permission for the current media to be played using that device.
If the user gives permission, the {{domxref("RemotePlayback.state","state")}} will be set to `connecting` and the user agent will connect to the device to initiate playback.
If the user chooses to instead disconnect from the device, the {{domxref("RemotePlayback.state","state")}} will be set to `disconnected` and user agent will disconnect from this device.
## Syntax
```js-nolint
prompt()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves with `undefined` after the user accepts or rejects the prompt.
### Exceptions
The promise will be rejected with one of the following exceptions:
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if {{domxref("HTMLMediaElement.disableRemotePlayback","disableRemotePlayback")}} is `true` for the media element.
- `OperationError` {{domxref("DOMException")}}
- : Thrown if there is already an unsettled promise from a previous call to `prompt()` for this media element, or browsing context.
- `InvalidAccessError` {{domxref("DOMException")}}
- : Thrown if the user has not interacted with this device recently.
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if the user agent knows that remote playback of this particular media is not feasible.
- `NotFoundError` {{domxref("DOMException")}}
- : Thrown if remote playback is unavailable.
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if the user denies permission to use the device.
## Security
[Transient user activation](/en-US/docs/Web/Security/User_activation) is required. The user has to interact with the page or a UI element in order for this feature to work.
## Examples
In the following example the user is prompted to select a remote playback device to play a video.
```js
devicesBtn.onclick = () => {
// Request the user to select a remote playback device.
videoElem.remote
.prompt()
// Update the UI and monitor the connected state.
.then(updateRemotePlaybackState);
// Otherwise, the user cancelled the selection UI or no screens were found.
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/remoteplayback | data/mdn-content/files/en-us/web/api/remoteplayback/connect_event/index.md | ---
title: "RemotePlayback: connect event"
short-title: connect
slug: Web/API/RemotePlayback/connect_event
page-type: web-api-event
browser-compat: api.RemotePlayback.connect_event
---
{{APIRef("Remote Playback API")}}
The **`connect`** event of the {{domxref("RemotePlayback")}} interface fires when the user agent connects to the remote device.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("connect", (event) => {});
onconnect = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Example
In the following example the value of {{domxref("RemotePlayback.state")}} is printed to the console when the user agent successfully connects.
```js
RemotePlayback.onconnect = () => {
console.log(RemotePlayback.state);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/remoteplayback | data/mdn-content/files/en-us/web/api/remoteplayback/state/index.md | ---
title: "RemotePlayback: state property"
short-title: state
slug: Web/API/RemotePlayback/state
page-type: web-api-instance-property
browser-compat: api.RemotePlayback.state
---
{{APIRef("Remote Playback API")}}
The **`state`** read-only property of the {{domxref("RemotePlayback")}} interface returns the current state of the `RemotePlayback` connection.
## Value
One of:
- `"connecting"`
- : The user agent is attempting to initiate remote playback with the selected device.
- `"connected"`
- : The transition from local to remote playback has happened. All commands will now take place on the remote device.
- `"disconnected"`
- : The remote playback has not been initiated, has failed to initiate, or has been stopped.
## Examples
In the following example the value of {{domxref("RemotePlayback.state")}} is printed to the console when the user agent successfully connects.
```js
RemotePlayback.onconnect = () => {
console.log(RemotePlayback.state);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/remoteplayback | data/mdn-content/files/en-us/web/api/remoteplayback/connecting_event/index.md | ---
title: "RemotePlayback: connecting event"
short-title: connecting
slug: Web/API/RemotePlayback/connecting_event
page-type: web-api-event
browser-compat: api.RemotePlayback.connecting_event
---
{{APIRef("Remote Playback API")}}
The **`connecting`** event of the {{domxref("RemotePlayback")}} interface fires when the user agent initiates remote playback.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("connecting", (event) => {});
onconnecting = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Example
In the following example the value of {{domxref("RemotePlayback.state")}} is printed to the console when the user agent initiates a connection.
```js
RemotePlayback.onconnecting = () => {
console.log(RemotePlayback.state);
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/remoteplayback | data/mdn-content/files/en-us/web/api/remoteplayback/watchavailability/index.md | ---
title: "RemotePlayback: watchAvailability() method"
short-title: watchAvailability()
slug: Web/API/RemotePlayback/watchAvailability
page-type: web-api-instance-method
browser-compat: api.RemotePlayback.watchAvailability
---
{{APIRef("Remote Playback API")}}
The **`watchAvailability()`** method of the {{domxref("RemotePlayback")}} interface watches the list of available remote playback devices and returns a {{jsxref("Promise")}} that resolves with the `callbackId` of a remote playback device.
## Syntax
```js-nolint
watchAvailability(RemotePlaybackAvailabilityCallback)
```
### Parameters
- `RemotePlaybackAvailabilityCallback(boolean)`
- : A callback that allows the page to obtain the remote playback device availability for the corresponding media element. It is passed a boolean which, if true, indicates that remote playback is available.
### Return value
A {{jsxref("Promise")}} that resolves with an integer. This is the `callbackId` for the identified remote playback device.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if {{domxref("HTMLMediaElement.disableRemotePlayback","disableRemotePlayback")}} is `true` for the media element.
- `NotSupportedError` {{domxref("DOMException")}}
- : Thrown if the user agent is unable to continuously monitor the list of available remote playback devices.
## Examples
In the following example, after checking that there is no currently connected device, `watchAvailability()` is used to watch for remote devices becoming available. [See the working example](https://beaufortfrancois.github.io/sandbox/media/remote-playback.html) (Requires a supported device and a connected remote playback device).
```js
if (video.remote.state === "disconnected") {
video.remote.watchAvailability(handleAvailabilityChange).then((id) => {
log(`> Started watching remote device availability: ${id}`);
callbackId = id;
});
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/remoteplayback | data/mdn-content/files/en-us/web/api/remoteplayback/cancelwatchavailability/index.md | ---
title: "RemotePlayback: cancelWatchAvailability() method"
short-title: cancelWatchAvailability()
slug: Web/API/RemotePlayback/cancelWatchAvailability
page-type: web-api-instance-method
browser-compat: api.RemotePlayback.cancelWatchAvailability
---
{{APIRef("Remote Playback API")}}
The **`cancelWatchAvailability()`** method of the {{domxref("RemotePlayback")}} interface cancels the request to watch for one or all available devices.
## Syntax
```js-nolint
cancelWatchAvailability()
cancelWatchAvailability(id)
```
### Parameters
- `id` {{optional_inline}}
- : The `callbackId` of a particular remote playback device.
If a `callbackId` of a specific device is passed in, then that device will be removed from the list of watched devices. Otherwise, the whole list will be cleared.
### Return value
A {{jsxref("Promise")}} that resolves with `undefined`.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if {{domxref("HTMLMediaElement.disableRemotePlayback","disableRemotePlayback")}} is `true` for the media element.
- `NotFoundError` {{domxref("DOMException")}}
- : Thrown if an `id` is passed but it does not match any available `callbackId`.
## Examples
Once a remote playback device has been identified and is connected, the monitoring of available devices can be stopped using `cancelWatchAvailability().`
```js
function switchToRemoteUI() {
// Indicate that the state is 'connecting' or 'connected' to the user.
// For example, hide the video element as only controls are needed.
videoElem.style.display = "none";
// Stop monitoring the availability of remote playback devices.
videoElem.remote.cancelWatchAvailability();
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/hiddevice/index.md | ---
title: HIDDevice
slug: Web/API/HIDDevice
page-type: web-api-interface
status:
- experimental
browser-compat: api.HIDDevice
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`HIDDevice`** interface of the {{domxref('WebHID API')}} represents a HID Device. It provides properties for accessing information about the device, methods for opening and closing the connection, and the sending and receiving of reports.
{{InheritanceDiagram}}
## Instance properties
This interface also inherits properties from {{domxref("EventTarget")}}.
- {{domxref("HIDDevice.opened")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a {{jsxref("boolean")}}, true if the device has an open connection.
- {{domxref("HIDDevice.vendorId")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the vendorId of the HID device.
- {{domxref("HIDDevice.productId")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns the productID of the HID device.
- {{domxref("HIDDevice.productName")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns a string containing the product name of the HID device.
- {{domxref("HIDDevice.collections")}} {{ReadOnlyInline}} {{Experimental_Inline}}
- : Returns an array of report formats for the HID device.
### Events
- {{domxref("HIDDevice.inputreport_event", "inputreport")}} {{Experimental_Inline}}
- : Fires when a report is sent from the device.
## Instance methods
This interface also inherits methods from {{domxref("EventTarget")}}.
- {{domxref("HIDDevice.open()")}} {{Experimental_Inline}}
- : Opens a connection to this HID device, and returns a {{jsxref("Promise")}} which resolves once the connection has been successful.
- {{domxref("HIDDevice.close()")}} {{Experimental_Inline}}
- : Closes the connection to this HID device, and returns a {{jsxref("Promise")}} which resolves once the connection has been closed.
- {{domxref("HIDDevice.forget()")}} {{Experimental_Inline}}
- : Closes the connection to this HID device and resets access permission, and returns a {{jsxref("Promise")}} which resolves once the permission was reset.
- {{domxref("HIDDevice.sendReport()")}} {{Experimental_Inline}}
- : Sends an output report to this HID Device, and returns a {{jsxref("Promise")}} which resolves once the report has been sent.
- {{domxref("HIDDevice.sendFeatureReport()")}} {{Experimental_Inline}}
- : Sends a feature report to this HID device, and returns a {{jsxref("Promise")}} which resolves once the report has been sent.
- {{domxref("HIDDevice.receiveFeatureReport()")}} {{Experimental_Inline}}
- : Receives a feature report from this HID device in the form of a {{jsxref("Promise")}} which resolves with a {{jsxref("DataView")}}. This allows typed access to the contents of this message.
## Examples
The following example demonstrates listening for an `inputreport` event that will allow the application to detect which button is pressed on a Joy-Con Right device.
```js
device.addEventListener("inputreport", (event) => {
const { data, device, reportId } = event;
// Handle only the Joy-Con Right device and a specific report ID.
if (device.productId !== 0x2007 && reportId !== 0x3f) return;
const value = data.getUint8(0);
if (value === 0) return;
const someButtons = { 1: "A", 2: "X", 4: "B", 8: "Y" };
console.log(`User pressed button ${someButtons[value]}.`);
});
```
In the following example `sendFeatureReport` is used to make a device blink.
```js
const reportId = 1;
for (let i = 0; i < 10; i++) {
// Turn off
await device.sendFeatureReport(reportId, Uint32Array.from([0, 0]));
await waitFor(100);
// Turn on
await device.sendFeatureReport(reportId, Uint32Array.from([512, 0]));
await waitFor(100);
}
```
You can see more examples, and live demos in the article [Connecting to uncommon HID devices](https://developer.chrome.com/docs/capabilities/hid).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/sendreport/index.md | ---
title: "HIDDevice: sendReport() method"
short-title: sendReport()
slug: Web/API/HIDDevice/sendReport
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.HIDDevice.sendReport
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`sendReport()`** method of the {{domxref("HIDDevice")}} interface sends an output report to the HID device.
The `reportId` for each of the report formats that this device supports can be retrieved from {{domxref("HIDDevice.collections")}}.
## Syntax
```js-nolint
sendReport(reportId, data)
```
### Parameters
- `reportId`
- : An 8-bit report ID. If the HID device does not use report IDs, send `0`.
- `data`
- : Bytes as an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}}.
### Return value
A {{jsxref("Promise")}} that resolves with `undefined` once the report has been sent.
### Exceptions
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if sending the report fails for any reason.
## Examples
The example below shows how to make a Joy-Con device rumble using output reports. You can see more examples, and live demos in the article [Connecting to uncommon HID devices](https://developer.chrome.com/docs/capabilities/hid).
```js
// First, send a command to enable vibration.
// Magical bytes come from https://github.com/mzyy94/joycon-toolweb
const enableVibrationData = [1, 0, 1, 64, 64, 0, 1, 64, 64, 0x48, 0x01];
await device.sendReport(0x01, new Uint8Array(enableVibrationData));
// Then, send a command to make the Joy-Con device rumble.
// Actual bytes are available in the sample.
const rumbleData = [
/* … */
];
await device.sendReport(0x10, new Uint8Array(rumbleData));
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/productname/index.md | ---
title: "HIDDevice: productName property"
short-title: productName
slug: Web/API/HIDDevice/productName
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.HIDDevice.productName
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`productName`** read-only property of the {{domxref("HIDDevice")}} interface returns the product name of the connected HID device.
## Value
A string.
## Examples
The following example retrieves devices with {{domxref("HID.getDevices()")}} and logs the value of `productName` to the console.
```js
document.addEventListener("DOMContentLoaded", async () => {
let devices = await navigator.hid.getDevices();
devices.forEach((device) => {
console.log(`HID: ${device.productName}`);
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/forget/index.md | ---
title: "HIDDevice: forget() method"
short-title: forget()
slug: Web/API/HIDDevice/forget
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.HIDDevice.forget
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`forget()`** method of the {{domxref("HIDDevice")}} interface closes the connection to the HID device and forgets the device.
## Syntax
```js-nolint
forget()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves with `undefined` once the connection is closed, the device is forgotten, and the permission is reset.
## Example
In the following example we connect to a Nintendo Switch Joy-Con Right HID device, blink once, and disconnect from it.
```js
async function blink() {
const devices = await navigator.hid.requestDevice({
filters: [
{
vendorId: 0x057e, // Nintendo Co., Ltd
productId: 0x2007, // Joy-Con Right
},
],
});
const device = devices[0];
await device.open();
// Turn off
await device.sendFeatureReport(reportId, Uint32Array.from([0, 0]));
await waitFor(100);
// Turn on
await device.sendFeatureReport(reportId, Uint32Array.from([512, 0]));
await new Promise((resolve) => setTimeout(resolve, 100));
// Finally, disconnect from it
await device.forget();
}
blink();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/receivefeaturereport/index.md | ---
title: "HIDDevice: receiveFeatureReport() method"
short-title: receiveFeatureReport()
slug: Web/API/HIDDevice/receiveFeatureReport
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.HIDDevice.receiveFeatureReport
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`receiveFeatureReport()`** method of the {{domxref("HIDDevice")}} interface receives a feature report from the HID device. Feature reports are a way for HID devices and applications to exchange non-standardized HID data.
The `reportId` for each of the report formats that this device supports can be retrieved from {{domxref("HIDDevice.collections")}}.
## Syntax
```js-nolint
receiveFeatureReport(reportId)
```
### Parameters
- `reportId`
- : An 8-bit report ID. If the HID device does not use report IDs, send `0`.
### Return value
A {{jsxref("Promise")}} which resolves with a {{jsxref("DataView")}} object containing the feature report.
### Exceptions
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if receiving the report fails for any reason.
## Examples
In the following example a report is received from a device using a `reportId` of `1`.
```js
const dataView = await device.receiveFeatureReport(1);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/productid/index.md | ---
title: "HIDDevice: productId property"
short-title: productId
slug: Web/API/HIDDevice/productId
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.HIDDevice.productId
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`productId`** read-only property of the {{domxref("HIDDevice")}} interface returns the product ID of the connected HID device.
## Value
An integer. If the device has no product ID, or the product ID cannot be accessed this will return `0`.
## Examples
The following example retrieves devices with {{domxref("HID.getDevices()")}} and logs the value of `productId` to the console.
```js
document.addEventListener("DOMContentLoaded", async () => {
let devices = await navigator.hid.getDevices();
devices.forEach((device) => {
console.log(`HID: ${device.productId}`);
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/sendfeaturereport/index.md | ---
title: "HIDDevice: sendFeatureReport() method"
short-title: sendFeatureReport()
slug: Web/API/HIDDevice/sendFeatureReport
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.HIDDevice.sendFeatureReport
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`sendFeatureReport()`** method of the {{domxref("HIDDevice")}} interface sends a feature report to the HID device. Feature reports are a way for HID devices and applications to exchange non-standardized HID data.
The `reportId` for each of the report formats that this device supports can be retrieved from {{domxref("HIDDevice.collections")}}.
## Syntax
```js-nolint
sendFeatureReport(reportId, data)
```
### Parameters
- `reportId`
- : An 8-bit report ID. If the HID device does not use report IDs, send `0`.
- `data`
- : Bytes as an {{jsxref("ArrayBuffer")}}, a {{jsxref("TypedArray")}}, or a {{jsxref("DataView")}}.
### Return value
A {{jsxref("Promise")}} that resolves with `undefined` once the report has been sent.
### Exceptions
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if sending the report fails for any reason.
## Examples
In the following example `sendFeatureReport()` makes a device blink. You can see more examples and live demos in the article [Connecting to uncommon HID devices](https://developer.chrome.com/docs/capabilities/hid).
```js
const reportId = 1;
for (let i = 0; i < 10; i++) {
// Turn off
await device.sendFeatureReport(reportId, Uint32Array.from([0, 0]));
await waitFor(100);
// Turn on
await device.sendFeatureReport(reportId, Uint32Array.from([512, 0]));
await waitFor(100);
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/collections/index.md | ---
title: "HIDDevice: collections property"
short-title: collections
slug: Web/API/HIDDevice/collections
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.HIDDevice.collections
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`collections`** read-only property of the {{domxref("HIDDevice")}} interface returns an array of report formats
## Value
An array of report formats. Each entry contains the following:
- `usagePage`
- : An integer representing the usage page component of the HID usage associated with this collection. The usage for a top level collection is used to identify the device type.
Standard HID usage values can be found in the [HID Usage Tables](https://usb.org/document-library/hid-usage-tables-13) document
- `usage`
- : An integer representing the usage ID component of the HID usage associated with this collection.
- `type`
- : An 8-bit value representing the collection type, which describes a different relationship between the grouped items. One of:
- `0x00`
- : Physical (group of axes)
- `0x01`
- : Application (mouse, keyboard)
- `0x02`
- : Logical (interrelated data)
- `0x03`
- : Report
- `0x04`
- : Named array
- `0x05`
- : Usage switch
- `0x06`
- : Usage modified
- `0x07 to 0x7F`
- : Reserved for future use
- `0x80 to 0xFF`
- : Vendor-defined
More information on these types can be found in the [Device Class Definition](https://www.usb.org/document-library/device-class-definition-hid-111) document.
- `children`
- : An array of sub-collections which takes the same format as a top-level collection.
- `inputReports`
- : An array of `inputReport` items which represent individual input reports described in this collection.
- `outputReports`
- : An array of `outputReport` items which represent individual output reports described in this collection.
- `featureReports`
- : An array of `featureReport` items which represent individual feature reports described in this collection.
## Examples
The following example demonstrates how to access the various elements once the `collections` property has been returned. You can see more examples, and live demos in the article [Connecting to uncommon HID devices](https://developer.chrome.com/docs/capabilities/hid).
```js
for (const collection of device.collections) {
// A HID collection includes usage, usage page, reports, and subcollections.
console.log(`Usage: ${collection.usage}`);
console.log(`Usage page: ${collection.usagePage}`);
for (const inputReport of collection.inputReports) {
console.log(`Input report: ${inputReport.reportId}`);
// Loop through inputReport.items
}
for (const outputReport of collection.outputReports) {
console.log(`Output report: ${outputReport.reportId}`);
// Loop through outputReport.items
}
for (const featureReport of collection.featureReports) {
console.log(`Feature report: ${featureReport.reportId}`);
// Loop through featureReport.items
}
// Loop through subcollections with collection.children
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/vendorid/index.md | ---
title: "HIDDevice: vendorId property"
short-title: vendorId
slug: Web/API/HIDDevice/vendorId
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.HIDDevice.vendorId
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`vendorId`** read-only property of the {{domxref("HIDDevice")}} interface returns the vendor ID of the connected HID device. This identifies the vendor of the device.
## Value
An integer. If the device has no vendor ID, or the vendor ID cannot be accessed this will return `0`.
## Examples
The following example retrieves devices with {{domxref("HID.getDevices()")}} and logs the value of `vendorId` to the console.
```js
document.addEventListener("DOMContentLoaded", async () => {
let devices = await navigator.hid.getDevices();
devices.forEach((device) => {
console.log(`HID: ${device.vendorId}`);
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/opened/index.md | ---
title: "HIDDevice: opened property"
short-title: opened
slug: Web/API/HIDDevice/opened
page-type: web-api-instance-property
status:
- experimental
browser-compat: api.HIDDevice.opened
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`opened`** read-only property of the {{domxref("HIDDevice")}} interface returns true if the connection to the {{domxref("HIDDevice")}} is open and ready to transfer data.
## Value
A boolean value, true if the connection is open.
## Examples
The following example retrieves devices with {{domxref("HID.getDevices()")}} and logs the value of `opened` to the console.
```js
document.addEventListener("DOMContentLoaded", async () => {
let devices = await navigator.hid.getDevices();
devices.forEach((device) => {
console.log(`HID: ${device.opened}`);
});
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/close/index.md | ---
title: "HIDDevice: close() method"
short-title: close()
slug: Web/API/HIDDevice/close
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.HIDDevice.close
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`close()`** method of the {{domxref("HIDDevice")}} interface closes the connection to the HID device.
## Syntax
```js-nolint
close()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves with `undefined` once the connection is closed.
## Examples
In the following example we close the HID device, once all data has been sent and received.
```js
await device.close();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/inputreport_event/index.md | ---
title: "HIDDevice: inputreport event"
short-title: inputreport
slug: Web/API/HIDDevice/inputreport_event
page-type: web-api-event
status:
- experimental
browser-compat: api.HIDDevice.inputreport_event
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`inputreport`** event of the {{domxref("HIDDevice")}} interface fires when a new report is received from the HID device.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("inputreport", (event) => {});
oninputreport = (event) => {};
```
## Event type
An {{domxref("HIDInputReportEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("HIDInputReportEvent")}}
## Event properties
_This interface also inherits properties from {{domxref("Event")}}._
- {{domxref("HIDInputReportEvent.data")}} {{ReadOnlyInline}}
- : A {{jsxref("DataView")}} containing the data from the input report, excluding the `reportId` if the HID interface uses report IDs.
- {{domxref("HIDInputReportEvent.device")}} {{ReadOnlyInline}}
- : The {{domxref("HIDDevice")}} instance that represents the HID interface that sent the input report.
- {{domxref("HIDInputReportEvent.reportId")}} {{ReadOnlyInline}}
- : The one-byte identification prefix for this report, or 0 if the HID interface does not use report IDs.
## Example
The following example demonstrates listening for an `inputreport` event that will allow the application to detect which button is pressed on a Joy-Con Right device. You can see more examples, and live demos in the article [Connecting to uncommon HID devices](https://developer.chrome.com/docs/capabilities/hid).
```js
device.addEventListener("inputreport", (event) => {
const { data, device, reportId } = event;
// Handle only the Joy-Con Right device and a specific report ID.
if (device.productId !== 0x2007 && reportId !== 0x3f) return;
const value = data.getUint8(0);
if (value === 0) return;
const someButtons = { 1: "A", 2: "X", 4: "B", 8: "Y" };
console.log(`User pressed button ${someButtons[value]}.`);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/hiddevice | data/mdn-content/files/en-us/web/api/hiddevice/open/index.md | ---
title: "HIDDevice: open() method"
short-title: open()
slug: Web/API/HIDDevice/open
page-type: web-api-instance-method
status:
- experimental
browser-compat: api.HIDDevice.open
---
{{securecontext_header}}{{APIRef("WebHID API")}}{{SeeCompatTable}}
The **`open()`** method of the {{domxref("HIDDevice")}} interface requests that the operating system opens the HID device.
> **Note:** HID devices are not opened automatically. Therefore, a {{domxref("HIDDevice")}} returned by {{domxref("HID.requestDevice()")}} must be opened with this method before it is available to transfer data.
## Syntax
```js-nolint
open()
```
### Parameters
None.
### Return value
A {{jsxref("Promise")}} that resolves with `undefined` once the connection is opened.
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if the connection is already open.
- `NotAllowedError` {{domxref("DOMException")}}
- : Thrown if the attempt to open the connection fails for any reason.
## Examples
In the following example, we wait for the HID connection to open before attempting to send or receive data.
```js
await device.open();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/cssrule/index.md | ---
title: CSSRule
slug: Web/API/CSSRule
page-type: web-api-interface
browser-compat: api.CSSRule
---
{{APIRef("CSSOM")}}
The **`CSSRule`** interface represents a single CSS rule. There are several types of rules which inherit properties from `CSSRule`.
- {{DOMXRef("CSSGroupingRule")}}
- {{DOMXRef("CSSStyleRule")}}
- {{DOMXRef("CSSImportRule")}}
- {{DOMXRef("CSSMediaRule")}}
- {{DOMXRef("CSSFontFaceRule")}}
- {{DOMXRef("CSSPageRule")}}
- {{DOMXRef("CSSNamespaceRule")}}
- {{DOMXRef("CSSKeyframesRule")}}
- {{DOMXRef("CSSKeyframeRule")}}
- {{DOMXRef("CSSCounterStyleRule")}}
- {{DOMXRef("CSSSupportsRule")}}
- {{DOMXRef("CSSFontFeatureValuesRule")}}
- {{DOMXRef("CSSFontPaletteValuesRule")}}
- {{DOMXRef("CSSLayerBlockRule")}}
- {{DOMXRef("CSSLayerStatementRule")}}
- {{DOMXRef("CSSPropertyRule")}}
## Instance properties
The `CSSRule` interface specifies the properties common to all rules, while properties unique to specific rule types are specified in the more specialized interfaces for those rules' respective types.
- {{domxref("CSSRule.cssText")}}
- : Represents the textual representation of the rule, e.g. "`h1,h2 { font-size: 16pt }`" or "`@import 'url'`". To access or modify parts of the rule (e.g. the value of "font-size" in the example) use the properties on the [specialized interface for the rule's type](#type_constants).
- {{domxref("CSSRule.parentRule")}} {{ReadOnlyInline}}
- : Returns the containing rule, otherwise `null`. E.g. if this rule is a style rule inside an {{cssxref("@media")}} block, the parent rule would be that {{domxref("CSSMediaRule")}}.
- {{domxref("CSSRule.parentStyleSheet")}} {{ReadOnlyInline}}
- : Returns the {{domxref("CSSStyleSheet")}} object for the style sheet that contains this rule
- {{domxref("CSSRule.type")}} {{ReadOnlyInline}} {{deprecated_inline}}
- : Returns one of the Type constants to determine which type of rule is represented.
## Examples
References to a `CSSRule` may be obtained by looking at a {{domxref("CSSStyleSheet")}}'s `cssRules` list.
```js
let myRules = document.styleSheets[0].cssRules; // Returns a CSSRuleList
console.log(myRules);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Using dynamic styling information](/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information)
| 0 |
data/mdn-content/files/en-us/web/api/cssrule | data/mdn-content/files/en-us/web/api/cssrule/parentrule/index.md | ---
title: "CSSRule: parentRule property"
short-title: parentRule
slug: Web/API/CSSRule/parentRule
page-type: web-api-instance-property
browser-compat: api.CSSRule.parentRule
---
{{ APIRef("CSSOM") }}
The **`parentRule`** property of the {{domxref("CSSRule")}}
interface returns the containing rule of the current rule if this exists, or otherwise
returns null.
## Value
A {{domxref("CSSRule")}} which is the type of the containing rules. If the current rule is inside a media query, this would return {{domxref("CSSMediaRule")}}. Otherwise it returns null.
## Examples
```css
@media (min-width: 500px) {
.box {
width: 100px;
height: 200px;
background-color: red;
}
body {
color: blue;
}
}
```
```js
let myRules = document.styleSheets[0].cssRules;
let childRules = myRules[0].cssRules;
console.log(childRules[0].parentRule); // a CSSMediaRule
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssrule | data/mdn-content/files/en-us/web/api/cssrule/csstext/index.md | ---
title: "CSSRule: cssText property"
short-title: cssText
slug: Web/API/CSSRule/cssText
page-type: web-api-instance-property
browser-compat: api.CSSRule.cssText
---
{{APIRef("CSSOM") }}
The **`cssText`** property of the {{domxref("CSSRule")}}
interface returns the actual text of a {{domxref("CSSStyleSheet")}} style-rule.
> **Note:** Do not confuse this property with element-style
> {{domxref("CSSStyleDeclaration.cssText")}}.
Be aware that this property can no longer be set directly, as it is [now specified](https://www.w3.org/TR/cssom-1/#changes-from-5-december-2013)
to be _functionally_ modify-only, and silently so. In other words, attempting to
set it _does absolutely nothing_, and doesn't even omit a warning or error.
Furthermore, it has no settable sub-properties. Therefore, to modify it, use the
stylesheet's {{domxref("CSSRuleList", "cssRules")}}`[index]` properties
{{domxref("CSSStyleRule.selectorText", ".selectorText")}} and
{{domxref("CSSStyleRule.style", ".style")}} (or its sub-properties). See [Using dynamic styling information](/en-US/docs/Web/API/CSS_Object_Model/Using_dynamic_styling_information) for details.
## Value
A string containing the actual text of the {{domxref("CSSStyleSheet")}} rule.
## Examples
```css
body {
background-color: darkblue;
}
```
```js
let stylesheet = document.styleSheets[0];
console.log(stylesheet.cssRules[0].cssText); // body { background-color: darkblue; }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssrule | data/mdn-content/files/en-us/web/api/cssrule/parentstylesheet/index.md | ---
title: "CSSRule: parentStyleSheet property"
short-title: parentStyleSheet
slug: Web/API/CSSRule/parentStyleSheet
page-type: web-api-instance-property
browser-compat: api.CSSRule.parentStyleSheet
---
{{ APIRef("CSSOM") }}
The **`parentStyleSheet`** property of the
{{domxref("CSSRule")}} interface returns the {{domxref("StyleSheet")}} object in which
the current rule is defined.
## Value
A {{domxref("StyleSheet")}} object.
## Examples
```js
const docRules = document.styleSheets[0].cssRules;
console.log(docRules[0].parentStyleSheet == document.styleSheets[0]); // returns true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/cssrule | data/mdn-content/files/en-us/web/api/cssrule/type/index.md | ---
title: "CSSRule: type property"
short-title: type
slug: Web/API/CSSRule/type
page-type: web-api-instance-property
status:
- deprecated
browser-compat: api.CSSRule.type
---
{{APIRef("CSSOM")}}{{Deprecated_header}}
The read-only **`type`** property of the
{{domxref("CSSRule")}} interface is a deprecated property that returns an integer
indicating which type of rule the {{domxref("CSSRule")}} represents.
If you need to distinguish different types of CSS rule, a good alternative is to use [`constructor.name`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name):
```js
const sheets = Array.from(document.styleSheets);
const rules = sheets.map((sheet) => Array.from(sheet.cssRules)).flat();
for (const rule of rules) {
console.log(rule.constructor.name);
}
```
## Value
- `CSSRule.STYLE_RULE` (`1`)
- : The rule is a {{domxref("CSSStyleRule")}}, the most common kind of rule: `selector { prop1: val1; prop2: val2; }`.
- `CSSRule.IMPORT_RULE` (`3`)
- : The rule is a {{domxref("CSSImportRule")}} and represents an {{cssxref("@import")}} rule.
- `CSSRule.MEDIA_RULE` (`4`)
- : The rule is a {{domxref("CSSMediaRule")}}.
- `CSSRule.FONT_FACE_RULE` (`5`)
- : The rule is a {{domxref("CSSFontFaceRule")}}
- `CSSRule.PAGE_RULE` (`6`)
- : The rule is a {{domxref("CSSPageRule")}}.
- `CSSRule.KEYFRAMES_RULE` (`7`)
- : The rule is a {{domxref("CSSKeyframesRule")}}.
- `CSSRule.KEYFRAME_RULE` (`8`)
- : The rule is a {{domxref("CSSKeyframeRule")}}.
- `CSSRule.NAMESPACE_RULE` (`10`)
- : The rule is a {{domxref("CSSNamespaceRule")}}.
- `CSSRule.COUNTER_STYLE_RULE` (`11`)
- : The rule is a {{domxref("CSSCounterStyleRule")}}.
- `CSSRule.SUPPORTS_RULE` (`12`)
- : The rule is a {{domxref("CSSSupportsRule")}}.
- `CSSRule.FONT_FEATURE_VALUES_RULE` (`14`)
- : The rule is a {{domxref("CSSFontFeatureValuesRule")}}.
The values `CSSRule.UNKNOWN_RULE` (`0`), `CSSRule.CHARSET_RULE` (`2`), `CSSRule.DOCUMENT_RULE` (`13`), `CSSRule.VIEWPORT_RULE` (`14`), and `CSSRule.REGION_STYLE_RULE` (`16`) cannot be obtained anymore.
## Examples
```js
const rules = document.styleSheets[0].cssRules;
console.log(rules[0].type);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/webglvertexarrayobject/index.md | ---
title: WebGLVertexArrayObject
slug: Web/API/WebGLVertexArrayObject
page-type: web-api-interface
browser-compat: api.WebGLVertexArrayObject
---
{{APIRef("WebGL")}}
The **`WebGLVertexArrayObject`** interface is part of the [WebGL 2 API](/en-US/docs/Web/API/WebGL_API), represents vertex array objects (VAOs) pointing to vertex array data, and provides names for different sets of vertex data.
{{InheritanceDiagram}}
When working with `WebGLVertexArrayObject` objects, the following methods are useful:
- {{domxref("WebGL2RenderingContext.createVertexArray()")}}
- {{domxref("WebGL2RenderingContext.deleteVertexArray()")}}
- {{domxref("WebGL2RenderingContext.isVertexArray()")}}
- {{domxref("WebGL2RenderingContext.bindVertexArray()")}}
> **Note:** The {{domxref("OES_vertex_array_object")}} extension allows you to use vertex array objects in a WebGL 1 context.
## Examples
```js
const vao = gl.createVertexArray();
gl.bindVertexArray(vao);
// …
// calls to bindBuffer or vertexAttribPointer
// which will be "recorded" in the VAO
// …
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{domxref("OES_vertex_array_object")}}
| 0 |
data/mdn-content/files/en-us/web/api | data/mdn-content/files/en-us/web/api/websocket/index.md | ---
title: WebSocket
slug: Web/API/WebSocket
page-type: web-api-interface
browser-compat: api.WebSocket
---
{{APIRef("WebSockets API")}}
The `WebSocket` object provides the API for creating and managing a [WebSocket](/en-US/docs/Web/API/WebSockets_API) connection to a server, as well as for sending and receiving data on the connection.
To construct a `WebSocket`, use the [`WebSocket()`](/en-US/docs/Web/API/WebSocket/WebSocket) constructor.
{{AvailableInWorkers}}
{{InheritanceDiagram}}
## Constructor
- {{domxref("WebSocket.WebSocket", "WebSocket()")}}
- : Returns a newly created `WebSocket` object.
## Instance properties
- {{domxref("WebSocket.binaryType")}}
- : The binary data type used by the connection.
- {{domxref("WebSocket.bufferedAmount")}} {{ReadOnlyInline}}
- : The number of bytes of queued data.
- {{domxref("WebSocket.extensions")}} {{ReadOnlyInline}}
- : The extensions selected by the server.
- {{domxref("WebSocket.protocol")}} {{ReadOnlyInline}}
- : The sub-protocol selected by the server.
- {{domxref("WebSocket.readyState")}} {{ReadOnlyInline}}
- : The current state of the connection.
- {{domxref("WebSocket.url")}} {{ReadOnlyInline}}
- : The absolute URL of the WebSocket.
## Instance methods
- {{domxref("WebSocket.close()")}}
- : Closes the connection.
- {{domxref("WebSocket.send()")}}
- : Enqueues data to be transmitted.
## Events
Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.
- {{domxref("WebSocket/close_event", "close")}}
- : Fired when a connection with a `WebSocket` is closed.
Also available via the `onclose` property
- {{domxref("WebSocket/error_event", "error")}}
- : Fired when a connection with a `WebSocket` has been closed because of an error, such as when some data couldn't be sent.
Also available via the `onerror` property.
- {{domxref("WebSocket/message_event", "message")}}
- : Fired when data is received through a `WebSocket`.
Also available via the `onmessage` property.
- {{domxref("WebSocket/open_event", "open")}}
- : Fired when a connection with a `WebSocket` is opened.
Also available via the `onopen` property.
## Examples
```js
// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");
// Connection opened
socket.addEventListener("open", (event) => {
socket.send("Hello Server!");
});
// Listen for messages
socket.addEventListener("message", (event) => {
console.log("Message from server ", event.data);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Writing WebSocket client applications](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications)
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/binarytype/index.md | ---
title: "WebSocket: binaryType property"
short-title: binaryType
slug: Web/API/WebSocket/binaryType
page-type: web-api-instance-property
browser-compat: api.WebSocket.binaryType
---
{{APIRef("WebSockets API")}}
The **`WebSocket.binaryType`** property controls the type of
binary data being received over the WebSocket connection.
## Value
A string:
- `"blob"`
- : Use {{domxref("Blob")}} objects for binary data. This is the default value.
- `"arraybuffer"`
- : Use {{jsxref("ArrayBuffer")}} objects for binary data.
## Examples
```js
// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");
// Change binary type from "blob" to "arraybuffer"
socket.binaryType = "arraybuffer";
// Listen for messages
socket.addEventListener("message", (event) => {
if (event.data instanceof ArrayBuffer) {
// binary frame
const view = new DataView(event.data);
console.log(view.getInt32(0));
} else {
// text frame
console.log(event.data);
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/open_event/index.md | ---
title: "WebSocket: open event"
short-title: open
slug: Web/API/WebSocket/open_event
page-type: web-api-event
browser-compat: api.WebSocket.open_event
---
{{APIRef("WebSockets API")}}
The `open` event is fired when a connection with a `WebSocket` is opened.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("open", (event) => {});
onopen = (event) => {};
```
## Event type
A generic {{domxref("Event")}}.
## Examples
```js
// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");
// Connection opened
socket.addEventListener("open", (event) => {
socket.send("Hello Server!");
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebSocket: close event](/en-US/docs/Web/API/WebSocket/close_event)
- [WebSocket: error event](/en-US/docs/Web/API/WebSocket/error_event)
- [WebSocket: message event](/en-US/docs/Web/API/WebSocket/message_event)
- [Writing WebSocket client applications](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications)
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/extensions/index.md | ---
title: "WebSocket: extensions property"
short-title: extensions
slug: Web/API/WebSocket/extensions
page-type: web-api-instance-property
browser-compat: api.WebSocket.extensions
---
{{APIRef("Web Sockets API")}}
The **`WebSocket.extensions`** read-only property returns the
extensions selected by the server. This is currently only the empty string or a list of
extensions as negotiated by the connection.
## Value
A string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/send/index.md | ---
title: "WebSocket: send() method"
short-title: send()
slug: Web/API/WebSocket/send
page-type: web-api-instance-method
browser-compat: api.WebSocket.send
---
{{APIRef("WebSockets API")}}
The **`WebSocket.send()`** method enqueues the specified data
to be transmitted to the server over the WebSocket connection, increasing the value of
`bufferedAmount` by the number of bytes needed to contain the data. If the
data can't be sent (for example, because it needs to be buffered but the buffer is
full), the socket is closed automatically.
The browser will throw an exception if you call `send()` when the connection is in the `CONNECTING` state. If you call `send()` when the connection is in the `CLOSING` or `CLOSED` states, the browser will silently discard the data.
## Syntax
```js-nolint
send(data)
```
### Parameters
- `data`
- : The data to send to the server. It may be one of the following types:
- `string`
- : A text string. The string is added to the buffer in UTF-8 format, and the value
of `bufferedAmount` is increased by the number of bytes required to
represent the UTF-8 string.
- {{jsxref("ArrayBuffer")}}
- : You can send the underlying binary data used by a typed array object; its binary
data contents are queued in the buffer, increasing the value of
`bufferedAmount` by the requisite number of bytes.
- {{domxref("Blob")}}
- : Specifying a `Blob` enqueues the blob's raw data to be transmitted in
a binary frame (the {{domxref("Blob.type")}} is ignored).
The value of `bufferedAmount` is increased by the byte size of that raw data.
- {{jsxref("TypedArray")}} or a {{jsxref("DataView")}}
- : You can send any [JavaScript typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) object as a binary frame;
its binary data contents are queued in the buffer,
increasing the value of `bufferedAmount` by the requisite number of bytes.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- `InvalidStateError` {{domxref("DOMException")}}
- : Thrown if {{domxref("WebSocket/readyState", "WebSocket.readyState")}} is `CONNECTING`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/close_event/index.md | ---
title: "WebSocket: close event"
short-title: close
slug: Web/API/WebSocket/close_event
page-type: web-api-event
browser-compat: api.WebSocket.close_event
---
{{APIRef("WebSockets API")}}
The `close` event is fired when a connection with a `WebSocket` is closed.
## Syntax
Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property.
```js
addEventListener("close", (event) => {});
onclose = (event) => {};
```
## Event type
A {{domxref("CloseEvent")}}. Inherits from {{domxref("Event")}}.
{{InheritanceDiagram("CloseEvent")}}
## Event properties
_In addition to the properties listed below, properties from the parent interface, {{domxref("Event")}}, are available._
- {{domxref("CloseEvent.code", "code")}} {{ReadOnlyInline}}
- : Returns an `unsigned short` containing the close code sent by the server.
- {{domxref("CloseEvent.reason", "reason")}} {{ReadOnlyInline}}
- : Returns a string indicating the reason the server closed the connection. This is specific to the particular server and sub-protocol.
- {{domxref("CloseEvent.wasClean", "wasClean")}} {{ReadOnlyInline}}
- : Returns a boolean value that Indicates whether or not the connection was cleanly closed.
## Examples
You might want to know when the connection has been closed so that you can update the UI or, perhaps, save data about the closed connection. Given that you have a variable called `exampleSocket` that refers to an opened `WebSocket`, this handler would handle the situation where the socket has been closed.
```js
exampleSocket.addEventListener("close", (event) => {
console.log("The connection has been closed successfully.");
});
```
You can perform the same actions using the event handler property, like this:
```js
exampleSocket.onclose = (event) => {
console.log("The connection has been closed successfully.");
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebSocket: error event](/en-US/docs/Web/API/WebSocket/error_event)
- [WebSocket: message event](/en-US/docs/Web/API/WebSocket/message_event)
- [WebSocket: open event](/en-US/docs/Web/API/WebSocket/open_event)
- [Writing WebSocket client applications](/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications)
| 0 |
data/mdn-content/files/en-us/web/api/websocket | data/mdn-content/files/en-us/web/api/websocket/url/index.md | ---
title: "WebSocket: url property"
short-title: url
slug: Web/API/WebSocket/url
page-type: web-api-instance-property
browser-compat: api.WebSocket.url
---
{{APIRef("WebSockets API")}}
The **`WebSocket.url`** read-only property returns the absolute
URL of the {{domxref("WebSocket")}} as resolved by the constructor.
## Value
A string.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 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.