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/sourcebuffer
data/mdn-content/files/en-us/web/api/sourcebuffer/audiotracks/index.md
--- title: "SourceBuffer: audioTracks property" short-title: audioTracks slug: Web/API/SourceBuffer/audioTracks page-type: web-api-instance-property browser-compat: api.SourceBuffer.audioTracks --- {{APIRef("Media Source Extensions")}} The **`audioTracks`** read-only property of the {{domxref("SourceBuffer")}} interface returns a list of the audio tracks currently contained inside the `SourceBuffer`. ## Value An {{domxref("AudioTrackList")}} object. ## Examples TBD ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaSource")}} - {{domxref("SourceBufferList")}}
0
data/mdn-content/files/en-us/web/api/sourcebuffer
data/mdn-content/files/en-us/web/api/sourcebuffer/appendwindowend/index.md
--- title: "SourceBuffer: appendWindowEnd property" short-title: appendWindowEnd slug: Web/API/SourceBuffer/appendWindowEnd page-type: web-api-instance-property browser-compat: api.SourceBuffer.appendWindowEnd --- {{APIRef("Media Source Extensions")}} The **`appendWindowEnd`** property of the {{domxref("SourceBuffer")}} interface controls the timestamp for the end of the [append window](https://w3c.github.io/media-source/#append-window), a timestamp range that can be used to filter what media data is appended to the `SourceBuffer`. Coded media frames with timestamps within this range will be appended, whereas those outside the range will be filtered out. The default value of `appendWindowEnd` is positive infinity. ## Value A double, indicating the end time of the append window, in seconds. ### Exceptions The following exceptions may be thrown when setting a new value for this property: - `InvalidAccessError` {{domxref("DOMException")}} - : Thrown if an attempt was made to set the value to less than or equal to {{domxref("SourceBuffer.appendWindowStart")}} or `NaN`. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if this {{domxref("SourceBuffer")}} object is being updated (i.e. its {{domxref("SourceBuffer.updating")}} property is currently `true`), or this `SourceBuffer` has been removed from the {{domxref("MediaSource")}}. ## Examples TBD ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaSource")}} - {{domxref("SourceBufferList")}}
0
data/mdn-content/files/en-us/web/api/sourcebuffer
data/mdn-content/files/en-us/web/api/sourcebuffer/changetype/index.md
--- title: "SourceBuffer: changeType() method" short-title: changeType() slug: Web/API/SourceBuffer/changeType page-type: web-api-instance-method browser-compat: api.SourceBuffer.changeType --- {{APIRef("Media Source Extensions")}} The **`changeType()`** method of the {{domxref("SourceBuffer")}} interface sets the MIME type that future calls to {{domxref("SourceBuffer.appendBuffer", "appendBuffer()")}} should expect the new media data to conform to. This makes it possible to change codecs or container type mid-stream. One scenario in which this is helpful is to support adapting the media source to changing bandwidth availability, by transitioning from one codec to another as resource constraints change. ## Syntax ```js-nolint changeType(type) ``` ### Parameters - `type` - : A string specifying the MIME type that future buffers will conform to. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the specified string is empty, rather than indicating a valid MIME type. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("SourceBuffer")}} is not a member of the parent media source's {{domxref("MediaSource.sourceBuffers", "sourceBuffers")}} list, or the buffer's {{domxref("SourceBuffer.updating", "updating")}} property indicates that a previously queued {{domxref("SourceBuffer.appendBuffer", "appendBuffer()")}} or {{domxref("SourceBuffer.remove", "remove()")}} is still being processed. - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the specified MIME type is not supported, or is not supported with the types of {{domxref("SourceBuffer")}} objects present in the {{domxref("MediaSource.sourceBuffers")}} list. ## Usage notes If the {{domxref("MediaSource.readyState", "readyState")}} property of the parent {{domxref("MediaSource")}} is set to `"ended"`, calling `changeType()` will set the `readyState` property to`"open"` and fire a simple event named {{domxref("MediaSource.sourceopen_event", "sourceopen")}} at the parent media source. ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaSource")}} - {{domxref("SourceBufferList")}}
0
data/mdn-content/files/en-us/web/api/sourcebuffer
data/mdn-content/files/en-us/web/api/sourcebuffer/updating/index.md
--- title: "SourceBuffer: updating property" short-title: updating slug: Web/API/SourceBuffer/updating page-type: web-api-instance-property browser-compat: api.SourceBuffer.updating --- {{APIRef("Media Source Extensions")}} The **`updating`** read-only property of the {{domxref("SourceBuffer")}} interface indicates whether the `SourceBuffer` is currently being updated β€” i.e. whether an {{domxref("SourceBuffer.appendBuffer()")}} or {{domxref("SourceBuffer.remove()")}} operation is currently in progress. ## Value A boolean value. ## Examples TBD ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaSource")}} - {{domxref("SourceBufferList")}}
0
data/mdn-content/files/en-us/web/api/sourcebuffer
data/mdn-content/files/en-us/web/api/sourcebuffer/abort/index.md
--- title: "SourceBuffer: abort() method" short-title: abort() slug: Web/API/SourceBuffer/abort page-type: web-api-instance-method browser-compat: api.SourceBuffer.abort --- {{APIRef("Media Source Extensions")}} The **`abort()`** method of the {{domxref("SourceBuffer")}} interface aborts the current segment and resets the segment parser. ## Syntax ```js-nolint abort() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the {{domxref("MediaSource.readyState")}} property of the parent media source is not equal to `open`, or this `SourceBuffer` has been removed from the {{domxref("MediaSource")}}. ## Examples The spec description of `abort()` is somewhat confusing β€” consider for example step 1 of [reset parser state](https://w3c.github.io/media-source/index.html#sourcebuffer-reset-parser-state). The MSE API is fully asynchronous, but this step seems to suggest a synchronous (blocking) operation, which doesn't make sense. Saying that, current implementations can be useful in certain situations, when you want to stop the current append (or whatever) operation occurring on a sourcebuffer, and then immediately start performing operations on it again. For example, consider this code: ```js sourceBuffer.addEventListener("updateend", (ev) => { // ... }); sourceBuffer.appendBuffer(buf); ``` Let's say that after the call to `appendBuffer` BUT before the `updateend` event fires (i.e. a buffer is being appended but the operation has not yet completed) a user "scrubs" the video seeking to a new point in time. In this case you would want to manually call `abort()` on the source buffer to stop the decoding of the current buffer, then fetch and append the newly requested segment that relates to the current new position of the video. You can see something similar in action in Nick Desaulnier's [bufferWhenNeeded demo](https://github.com/nickdesaulniers/netfix/blob/gh-pages/demo/bufferWhenNeeded.html) β€” in [line 48, an event listener is added to the playing video](https://github.com/nickdesaulniers/netfix/blob/gh-pages/demo/bufferWhenNeeded.html#L48) so a function called `seek()` is run when the `seeking` event fires. In [lines 92-101, the seek() function is defined](https://github.com/nickdesaulniers/netfix/blob/gh-pages/demo/bufferWhenNeeded.html#L92-L101) β€” note that `abort()` is called if {{domxref("MediaSource.readyState")}} is set to `open`, which means that it is ready to receive new source buffers β€” at this point it is worth aborting the current segment and just getting the one for the new seek position (see [`checkBuffer()`](https://github.com/nickdesaulniers/netfix/blob/gh-pages/demo/bufferWhenNeeded.html#L78-L90) and [`getCurrentSegment()`](https://github.com/nickdesaulniers/netfix/blob/gh-pages/demo/bufferWhenNeeded.html#L103-L105).) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaSource")}} - {{domxref("SourceBufferList")}}
0
data/mdn-content/files/en-us/web/api/sourcebuffer
data/mdn-content/files/en-us/web/api/sourcebuffer/timestampoffset/index.md
--- title: "SourceBuffer: timestampOffset property" short-title: timestampOffset slug: Web/API/SourceBuffer/timestampOffset page-type: web-api-instance-property browser-compat: api.SourceBuffer.timestampOffset --- {{APIRef("Media Source Extensions")}} The **`timestampOffset`** property of the {{domxref("SourceBuffer")}} interface controls the offset applied to timestamps inside media segments that are appended to the `SourceBuffer`. The initial value of `timestampOffset` is 0. ## Value A double, with the offset amount expressed in seconds. ### Exceptions The following exception may be thrown when setting a new value for this property: - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if one or more of the {{domxref("SourceBuffer")}} objects in {{domxref("MediaSource.sourceBuffers")}} are being updated (i.e. their {{domxref("SourceBuffer.updating")}} property is currently `true`), a media segment inside the `SourceBuffer` is currently being parsed, or this `SourceBuffer` has been removed from the {{domxref("MediaSource")}}. ## Examples TBD ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaSource")}} - {{domxref("SourceBufferList")}}
0
data/mdn-content/files/en-us/web/api/sourcebuffer
data/mdn-content/files/en-us/web/api/sourcebuffer/videotracks/index.md
--- title: "SourceBuffer: videoTracks property" short-title: videoTracks slug: Web/API/SourceBuffer/videoTracks page-type: web-api-instance-property browser-compat: api.SourceBuffer.videoTracks --- {{APIRef("Media Source Extensions")}} The **`videoTracks`** read-only property of the {{domxref("SourceBuffer")}} interface returns a list of the video tracks currently contained inside the `SourceBuffer`. ## Value An {{domxref("VideoTrackList")}} object. ## Examples TBD ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaSource")}} - {{domxref("SourceBufferList")}}
0
data/mdn-content/files/en-us/web/api/sourcebuffer
data/mdn-content/files/en-us/web/api/sourcebuffer/appendwindowstart/index.md
--- title: "SourceBuffer: appendWindowStart property" short-title: appendWindowStart slug: Web/API/SourceBuffer/appendWindowStart page-type: web-api-instance-property browser-compat: api.SourceBuffer.appendWindowStart --- {{APIRef("Media Source Extensions")}} The **`appendWindowStart`** property of the {{domxref("SourceBuffer")}} interface controls the timestamp for the start of the [append window](https://w3c.github.io/media-source/#append-window), a timestamp range that can be used to filter what media data is appended to the `SourceBuffer`. Coded media frames with timestamps within this range will be appended, whereas those outside the range will be filtered out. The default value of `appendWindowStart` is the presentation start time, which is the beginning time of the playable media. ## Value A double, indicating the start time of the append window, in seconds. ### Exceptions The following exceptions may be thrown when setting a new value for this property: - `InvalidAccessError` {{domxref("DOMException")}} - : Thrown if an attempt was made to set the value to less than 0 or to a value greater than or equal to {{domxref("SourceBuffer.appendWindowEnd")}}. - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if this {{domxref("SourceBuffer")}} object is being updated (i.e. its {{domxref("SourceBuffer.updating")}} property is currently `true`), or this `SourceBuffer` has been removed from the {{domxref("MediaSource")}}. ## Examples TBD ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("MediaSource")}} - {{domxref("SourceBufferList")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/oes_texture_half_float/index.md
--- title: OES_texture_half_float extension short-title: OES_texture_half_float slug: Web/API/OES_texture_half_float page-type: webgl-extension browser-compat: api.OES_texture_half_float --- {{APIRef("WebGL")}} The **`OES_texture_half_float`** extension is part of the [WebGL API](/en-US/docs/Web/API/WebGL_API) and adds texture formats with 16- (aka half float) and 32-bit floating-point components. WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial). > **Note:** This extension is only available to {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} contexts. In {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}}, the functionality of this extension is available on the WebGL2 context by default. The constant in WebGL2 is `gl.HALF_FLOAT`. ## Constants - `ext.HALF_FLOAT_OES` - : Half floating-point type (16-bit). ## Extended methods This extension extends {{domxref("WebGLRenderingContext.texImage2D()")}} and {{domxref("WebGLRenderingContext.texSubImage2D()")}}: - The `type` parameter now accepts `ext.HALF_FLOAT_OES`. ## Limitation: Linear filtering Linear filtering on half floating-point textures is not allowed with this extension. If you set the magnification or minification filter in the {{domxref("WebGLRenderingContext.texParameter()")}} method to one of `gl.LINEAR`, `gl.LINEAR_MIPMAP_NEAREST`, `gl.NEAREST_MIPMAP_LINEAR`, or `gl.LINEAR_MIPMAP_LINEAR`, and use half floating-point textures, the texture will be marked as incomplete. To use linear filtering on half floating-point textures, enable the {{domxref("OES_texture_half_float_linear")}} extension in addition to this extension. ## Half floating-point color buffers This extension implicitly enables the {{domxref("EXT_color_buffer_half_float")}} extension (if supported), which allows rendering to 16-bit floating point formats. ## Examples ```js const ext = gl.getExtension("OES_texture_half_float"); const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, ext.HALF_FLOAT_OES, image); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("WebGLRenderingContext.getExtension()")}} - {{domxref("WebGLRenderingContext.texImage2D()")}} - {{domxref("WebGLRenderingContext.texSubImage2D()")}} - {{domxref("OES_texture_float")}} - {{domxref("OES_texture_float_linear")}} - {{domxref("OES_texture_half_float_linear")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/svgfeimageelement/index.md
--- title: SVGFEImageElement slug: Web/API/SVGFEImageElement page-type: web-api-interface browser-compat: api.SVGFEImageElement --- {{APIRef("SVG")}} The **`SVGFEImageElement`** interface corresponds to the {{SVGElement("feImage")}} element. {{InheritanceDiagram}} ## Instance properties _This interface also inherits properties from its parent interface, {{domxref("SVGElement")}}._ - {{domxref("SVGFEImageElement.crossOrigin")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} reflects the {{SVGAttr("crossorigin")}} attribute of the given element, limited to only known values. - {{domxref("SVGFEImageElement.height")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("height")}} attribute of the given element. - {{domxref("SVGFEImageElement.href")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} that reflects the {{SVGAttr("href")}} or {{SVGAttr("xlink:href")}} {{deprecated_inline}} attribute of the given element. - {{domxref("SVGFEImageElement.preserveAspectRatio")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedPreserveAspectRatio")}} corresponding to the {{SVGAttr("preserveAspectRatio")}} attribute of the given element. - {{domxref("SVGFEImageElement.result")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedString")}} corresponding to the {{SVGAttr("result")}} attribute of the given element. - {{domxref("SVGFEImageElement.width")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("width")}} attribute of the given element. - {{domxref("SVGFEImageElement.x")}} {{ReadOnlyInline}} - : An {{domxref("SVGAnimatedLength")}} corresponding to the {{SVGAttr("x")}} attribute of the given element. - {{domxref("SVGFEImageElement.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("feImage")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/formdata/index.md
--- title: FormData slug: Web/API/FormData page-type: web-api-interface browser-compat: api.FormData --- {{APIRef("XMLHttpRequest API")}} The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the {{domxref("fetch()")}}, {{domxref("XMLHttpRequest.send()")}} or {{domxref("navigator.sendBeacon()")}} methods. It uses the same format a form would use if the encoding type were set to `"multipart/form-data"`. You can also pass it directly to the {{domxref("URLSearchParams")}} constructor if you want to generate query parameters in the way a {{HTMLElement("form")}} would do if it were using simple `GET` submission. An object implementing `FormData` can directly be used in a {{jsxref("Statements/for...of", "for...of")}} structure, instead of {{domxref('FormData.entries()', 'entries()')}}: `for (const p of myFormData)` is equivalent to `for (const p of myFormData.entries())`. {{AvailableInWorkers}} ## Constructor - {{domxref("FormData.FormData","FormData()")}} - : Creates a new `FormData` object. ## Instance methods - {{domxref("FormData.append()")}} - : Appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - {{domxref("FormData.delete()")}} - : Deletes a key/value pair from a `FormData` object. - {{domxref("FormData.entries()")}} - : Returns an [iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) that iterates through all key/value pairs contained in the `FormData`. - {{domxref("FormData.get()")}} - : Returns the first value associated with a given key from within a `FormData` object. - {{domxref("FormData.getAll()")}} - : Returns an array of all the values associated with a given key from within a `FormData`. - {{domxref("FormData.has()")}} - : Returns whether a `FormData` object contains a certain key. - {{domxref("FormData.keys()")}} - : Returns an [iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) iterates through all keys of the key/value pairs contained in the `FormData`. - {{domxref("FormData.set()")}} - : Sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - {{domxref("FormData.values()")}} - : Returns an [iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) that iterates through all values contained in the `FormData`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api/formdata
data/mdn-content/files/en-us/web/api/formdata/get/index.md
--- title: "FormData: get() method" short-title: get() slug: Web/API/FormData/get page-type: web-api-instance-method browser-compat: api.FormData.get --- {{APIRef("XMLHttpRequest API")}} The **`get()`** method of the {{domxref("FormData")}} interface returns the first value associated with a given key from within a `FormData` object. If you expect multiple values and want all of them, use the {{domxref("FormData.getAll()","getAll()")}} method instead. {{AvailableInWorkers}} ## Syntax ```js-nolint get(name) ``` ### Parameters - `name` - : A string representing the name of the key you want to retrieve. ### Return value A value whose key matches the specified `name`. Otherwise, [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null). ## Examples If we add two `username` values to a {{domxref("FormData")}} using {{domxref("FormData.append", "append()")}}: ```js formData.append("username", "Chris"); formData.append("username", "Bob"); ``` The following `get()` method will only return the first `username` value: ```js formData.get("username"); // Returns "Chris" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api/formdata
data/mdn-content/files/en-us/web/api/formdata/has/index.md
--- title: "FormData: has() method" short-title: has() slug: Web/API/FormData/has page-type: web-api-instance-method browser-compat: api.FormData.has --- {{APIRef("XMLHttpRequest API")}} The **`has()`** method of the {{domxref("FormData")}} interface returns whether a `FormData` object contains a certain key. {{AvailableInWorkers}} ## Syntax ```js-nolint has(name) ``` ### Parameters - `name` - : A string representing the name of the key you want to test for. ### Return value `true` if a key of `FormData` matches the specified `name`. Otherwise, `false`. ## Examples The following snippet shows the results of testing for the existence of `username` in a `FormData` object, before and after appending a `username` value to it with {{domxref("FormData.append", "append()")}}: ```js formData.has("username"); // Returns false formData.append("username", "Chris"); formData.has("username"); // Returns true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api/formdata
data/mdn-content/files/en-us/web/api/formdata/set/index.md
--- title: "FormData: set() method" short-title: set() slug: Web/API/FormData/set page-type: web-api-instance-method browser-compat: api.FormData.set --- {{APIRef("XMLHttpRequest API")}} The **`set()`** method of the {{domxref("FormData")}} interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. The difference between `set()` and {{domxref("FormData.append", "append()")}} is that if the specified key does already exist, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. {{AvailableInWorkers}} ## Syntax ```js-nolint set(name, value) set(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The field's value. This can be a string or {{domxref("Blob")}} (including subclasses such as {{domxref("File")}}). If none of these are specified the value is converted to a string. - `filename` {{optional_inline}} - : The filename reported to the server (a string), when a {{domxref("Blob")}} or {{domxref("File")}} is passed as the second parameter. The default filename for {{domxref("Blob")}} objects is "blob". The default filename for {{domxref("File")}} objects is the file's filename. > **Note:** If you specify a {{domxref("Blob")}} as the data to append to the `FormData` object, the filename that will be reported to the server in the "Content-Disposition" header used to vary from browser to browser. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js formData.set("username", "Chris"); ``` When the value is a {{domxref("Blob")}} (or a {{domxref("File")}}), you can specify its name with the `filename` parameter: ```js formData.set("userpic", myFileInput.files[0], "chris.jpg"); ``` If the value is not a string or a `Blob`, `set()` will convert it to a string automatically: ```js formData.set("name", 72); formData.get("name"); // "72" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api/formdata
data/mdn-content/files/en-us/web/api/formdata/append/index.md
--- title: "FormData: append() method" short-title: append() slug: Web/API/FormData/append page-type: web-api-instance-method browser-compat: api.FormData.append --- {{APIRef("XMLHttpRequest API")}} The **`append()`** method of the {{domxref("FormData")}} interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. The difference between {{domxref("FormData.set", "set()")}} and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. {{AvailableInWorkers}} ## Syntax ```js-nolint append(name, value) append(name, value, filename) ``` ### Parameters - `name` - : The name of the field whose data is contained in `value`. - `value` - : The field's value. This can be a string or {{domxref("Blob")}} (including subclasses such as {{domxref("File")}}). If none of these are specified the value is converted to a string. - `filename` {{optional_inline}} - : The filename reported to the server (a string), when a {{domxref("Blob")}} or {{domxref("File")}} is passed as the second parameter. The default filename for {{domxref("Blob")}} objects is "blob". The default filename for {{domxref("File")}} objects is the file's filename. > **Note:** If you specify a {{domxref("Blob")}} as the data to append to the `FormData` object, the filename that will be reported to the server in the "Content-Disposition" header used to vary from browser to browser. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js formData.append("username", "Chris"); ``` When the value is a {{domxref("Blob")}} (or a {{domxref("File")}}), you can specify its name with the `filename` parameter: ```js formData.append("userpic", myFileInput.files[0], "chris.jpg"); ``` As with regular form data, you can append multiple values with the same name: ```js formData.append("userpic", myFileInput.files[0], "chris1.jpg"); formData.append("userpic", myFileInput.files[1], "chris2.jpg"); ``` If the value is not a string or a `Blob`, `append()` will convert it to a string automatically: ```js formData.append("name", true); formData.append("name", 72); formData.getAll("name"); // ["true", "72"] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api/formdata
data/mdn-content/files/en-us/web/api/formdata/keys/index.md
--- title: "FormData: keys() method" short-title: keys() slug: Web/API/FormData/keys page-type: web-api-instance-method browser-compat: api.FormData.keys --- {{APIRef("XMLHttpRequest API")}} The **`FormData.keys()`** method returns an [iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) which iterates through all keys contained in the {{domxref("FormData")}}. The keys are strings. {{AvailableInWorkers}} ## Syntax ```js-nolint keys() ``` ### Parameters None. ### Return value An [`iterator`](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of {{domxref("FormData")}}'s keys. ## Examples ```js const formData = new FormData(); formData.append("key1", "value1"); formData.append("key2", "value2"); // Display the keys for (const key of formData.keys()) { console.log(key); } ``` The result is: ```plain key1 key2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api/formdata
data/mdn-content/files/en-us/web/api/formdata/values/index.md
--- title: "FormData: values() method" short-title: values() slug: Web/API/FormData/values page-type: web-api-instance-method browser-compat: api.FormData.values --- {{APIRef("XMLHttpRequest API")}} The **`FormData.values()`** method returns an [iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) which iterates through all values contained in the {{domxref("FormData")}}. The values are strings or {{domxref("Blob")}} objects. {{AvailableInWorkers}} ## Syntax ```js-nolint values() ``` ### Parameters None. ### Return value An [`iterator`](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of {{domxref("FormData")}}'s values. ## Examples ```js const formData = new FormData(); formData.append("key1", "value1"); formData.append("key2", "value2"); // Display the values for (const value of formData.values()) { console.log(value); } ``` The result is: ```plain value1 value2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api/formdata
data/mdn-content/files/en-us/web/api/formdata/delete/index.md
--- title: "FormData: delete() method" short-title: delete() slug: Web/API/FormData/delete page-type: web-api-instance-method browser-compat: api.FormData.delete --- {{APIRef("XMLHttpRequest API")}} The **`delete()`** method of the {{domxref("FormData")}} interface deletes a key and its value(s) from a `FormData` object. {{AvailableInWorkers}} ## Syntax ```js-nolint delete(name) ``` ### Parameters - `name` - : The name of the key you want to delete. ### Return value None ({{jsxref("undefined")}}). ## Examples You can delete a key and its values using `delete()`: ```js formData.delete("username"); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api/formdata
data/mdn-content/files/en-us/web/api/formdata/getall/index.md
--- title: "FormData: getAll() method" short-title: getAll() slug: Web/API/FormData/getAll page-type: web-api-instance-method browser-compat: api.FormData.getAll --- {{APIRef("XMLHttpRequest API")}} The **`getAll()`** method of the {{domxref("FormData")}} interface returns all the values associated with a given key from within a `FormData` object. {{AvailableInWorkers}} ## Syntax ```js-nolint getAll(name) ``` ### Parameters - `name` - : A string representing the name of the key you want to retrieve. ### Return value An array of values whose key matches the specified `name`. Otherwise, an empty list. ## Examples If we add two `username` values to a {{domxref("FormData")}} using {{domxref("FormData.append", "append()")}}: ```js formData.append("username", "Chris"); formData.append("username", "Bob"); ``` The following `getAll()` method will return both `username` values in an array: ```js formData.getAll("username"); // Returns ["Chris", "Bob"] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api/formdata
data/mdn-content/files/en-us/web/api/formdata/formdata/index.md
--- title: "FormData: FormData() constructor" short-title: FormData() slug: Web/API/FormData/FormData page-type: web-api-constructor browser-compat: api.FormData.FormData --- {{APIRef("XMLHttpRequest API")}} The **`FormData()`** constructor creates a new {{domxref("FormData")}} object. {{AvailableInWorkers}} ## Syntax ```js-nolint new FormData() new FormData(form) new FormData(form, submitter) ``` ### Parameters - `form` {{optional_inline}} - : An HTML {{HTMLElement("form")}} element β€” when specified, the {{domxref("FormData")}} object will be populated with the `form`'s current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content. - `submitter` {{optional_inline}} - : A {{Glossary("submit button")}} that is a member of the `form`. If the `submitter` has a `name` attribute or is an `{{HtmlElement('input/image', '&lt;input type="image"&gt;')}}`, its data [will be included](/en-US/docs/Glossary/Submit_button#form_data_entries) in the {{domxref("FormData")}} object (e.g. `btnName=btnValue`). ### Exceptions - {{jsxref("TypeError")}} - : Thrown if the specified `submitter` is not a {{Glossary("submit button")}}. - `NotFoundError` {{domxref("DOMException")}} - : Thrown if the specified `submitter` isn't a member of the `form`. The `submitter` must be either a descendant of the form element or must have a [`form`](/en-US/docs/Web/HTML/Element/input#form) attribute referring to the form. ## Examples ### Creating an empty FormData The following line creates an empty {{domxref("FormData")}} object: ```js const formData = new FormData(); ``` You could add a key/value pair to this using {{domxref("FormData.append", "append()")}}: ```js formData.append("username", "Chris"); ``` ### Prepopulating from a HTML form element You can specify the optional `form` and `submitter` arguments when creating the `FormData` object, to prepopulate it with values from the specified form. > **Note:** Only successful form controls are included in a FormData object, i.e. those with a name and not in a disabled state. #### HTML ```html <form id="form"> <input type="text" name="text1" value="foo" /> <input type="text" name="text2" value="bar" /> <input type="text" name="text2" value="baz" /> <input type="checkbox" name="check" checked disabled /> <button name="intent" value="save">Save</button> <button name="intent" value="saveAsCopy">Save As Copy</button> </form> <output id="output"></output> ``` ```css hidden form { display: none; } output { display: block; white-space: pre-wrap; } ``` #### JavaScript ```js const form = document.getElementById("form"); const submitter = document.querySelector("button[value=save]"); const formData = new FormData(form, submitter); const output = document.getElementById("output"); for (const [key, value] of formData) { output.textContent += `${key}: ${value}\n`; } ``` #### Result For brevity, the `<form>` element is hidden from view. {{EmbedLiveSample("prepopulating_from_a_html_form_element", "", 150)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api/formdata
data/mdn-content/files/en-us/web/api/formdata/entries/index.md
--- title: "FormData: entries() method" short-title: entries() slug: Web/API/FormData/entries page-type: web-api-instance-method browser-compat: api.FormData.entries --- {{APIRef("XMLHttpRequest API")}} The **`FormData.entries()`** method returns an [iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) which iterates through all key/value pairs contained in the {{domxref("FormData")}}. The key of each pair is a string object, and the value is either a string or a {{domxref("Blob")}}. {{AvailableInWorkers}} ## Syntax ```js-nolint entries() ``` ### Parameters None. ### Return value An [iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of {{domxref("FormData")}}'s key/value pairs. ## Examples ```js formData.append("key1", "value1"); formData.append("key2", "value2"); // Display the key/value pairs for (const pair of formData.entries()) { console.log(pair[0], pair[1]); } ``` The result is: ```plain key1 value1 key2 value2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using FormData objects](/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects) - {{HTMLElement("Form")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/file_system_api/index.md
--- title: File System API slug: Web/API/File_System_API page-type: web-api-overview browser-compat: - api.FileSystemHandle - api.FileSystemFileHandle --- {{securecontext_header}}{{DefaultAPISidebar("File System API")}} The File System API β€” with extensions provided via the [File System Access API](https://wicg.github.io/file-system-access/) to access files on the device file system β€” allows read, write and file management capabilities. ## Concepts and Usage This API allows interaction with files on a user's local device, or on a user-accessible network file system. Core functionality of this API includes reading files, writing or saving files, and access to directory structure. Most of the interaction with files and directories is accomplished through handles. A parent {{domxref('FileSystemHandle')}} class helps define two child classes: {{domxref('FileSystemFileHandle')}} and {{domxref('FileSystemDirectoryHandle')}}, for files and directories respectively. The handles represent a file or directory on the user's system. You can first gain access to them by showing the user a file or directory picker using methods such as {{domxref('window.showOpenFilePicker()')}} and {{domxref('window.showDirectoryPicker()')}}. Once these are called, the file picker presents itself and the user selects either a file or directory. Once this happens successfully, a handle is returned. You can also gain access to file handles via: - The {{domxref('DataTransferItem.getAsFileSystemHandle()')}} method of the {{domxref('HTML Drag and Drop API', 'HTML Drag and Drop API', '', 'nocode')}}. - The [File Handling API](https://developer.chrome.com/en/articles/file-handling/). Each handle provides its own functionality and there are a few differences depending on which one you are using (see the [interfaces](#interfaces) section for specific details). You then can access file data, or information (including children) of the directory selected. This API opens up potential functionality the web has been lacking. Still, security has been of utmost concern when designing the API, and access to file/directory data is disallowed unless the user specifically permits it (note that this is not the case with the [Origin private file system](#origin_private_file_system), because it is not visible to the user). > **Note:** The different exceptions that can be thrown when using the features of this API are listed on relevant pages as defined in the spec. However, the situation is made more complex by the interaction of the API and the underlying operating system. A proposal has been made to [list the error mappings in the spec](https://github.com/whatwg/fs/issues/57), which includes useful related information. > **Note:** Objects based on {{domxref("FileSystemHandle")}} can also be serialized into an {{domxref("IndexedDB API", "IndexedDB", "", "nocode")}} database instance, or transferred via {{domxref("window.postMessage", "postMessage()")}}. ### Origin private file system The origin private file system (OPFS) is a storage endpoint provided as part of the File System API, which is private to the origin of the page and not visible to the user like the regular file system. It provides access to a special kind of file that is highly optimized for performance and offers in-place write access to its content. Read our [Origin private file system](/en-US/docs/Web/API/File_System_API/Origin_private_file_system) for instructions on how to use it. ### Saving files - In the case of the asynchronous handles, use the {{domxref('FileSystemWritableFileStream')}} interface. Once the data you'd like to save is in a format of {{domxref('Blob')}}, {{jsxref("String")}} object, string literal or {{jsxref('ArrayBuffer', 'buffer')}}, you can open a stream and save the data to a file. This can be the existing file or a new file. - In the case of the synchronous {{domxref('FileSystemSyncAccessHandle')}}, you write changes to a file using the {{domxref('FileSystemSyncAccessHandle.write', 'write()')}} method. You can optionally also call {{domxref('FileSystemSyncAccessHandle.flush', 'flush()')}} if you need the changes committed to disk at a specific time (otherwise you can leave the underlying operating system to handle this when it sees fit, which should be OK in most cases). ## Interfaces - {{domxref("FileSystemHandle")}} - : The **`FileSystemHandle`** interface is an object which represents an entry. Multiple handles can represent the same entry. For the most part you do not work with `FileSystemHandle` directly but rather its child interfaces {{domxref('FileSystemFileHandle')}} and {{domxref('FileSystemDirectoryHandle')}}. - {{domxref("FileSystemFileHandle")}} - : Provides a handle to a file system entry. - {{domxref("FileSystemDirectoryHandle")}} - : provides a handle to a file system directory. - {{domxref("FileSystemSyncAccessHandle")}} - : Provides a synchronous handle to a file system entry, which operates in-place on a single file on disk. The synchronous nature of the file reads and writes allows for higher performance for critical methods in contexts where asynchronous operations come with high overhead, e.g., [WebAssembly](/en-US/docs/WebAssembly). This class is only accessible inside dedicated [Web Workers](/en-US/docs/Web/API/Web_Workers_API) for files within the [origin private file system](#origin_private_file_system). - {{domxref("FileSystemWritableFileStream")}} - : is a {{domxref('WritableStream')}} object with additional convenience methods, which operates on a single file on disk. ## Examples ### Accessing files The below code allows the user to choose a file from the file picker. ```js async function getFile() { // Open file picker and destructure the result the first handle const [fileHandle] = await window.showOpenFilePicker(); const file = await fileHandle.getFile(); return file; } ``` The following asynchronous function presents a file picker and once a file is chosen, uses the `getFile()` method to retrieve the contents. ```js const pickerOpts = { types: [ { description: "Images", accept: { "image/*": [".png", ".gif", ".jpeg", ".jpg"], }, }, ], excludeAcceptAllOption: true, multiple: false, }; async function getTheFile() { // Open file picker and destructure the result the first handle const [fileHandle] = await window.showOpenFilePicker(pickerOpts); // get file contents const fileData = await fileHandle.getFile(); } ``` ### Accessing directories The following example returns a directory handle with the specified name. If the directory does not exist, it is created. ```js const dirName = "directoryToGetName"; // assuming we have a directory handle: 'currentDirHandle' const subDir = currentDirHandle.getDirectoryHandle(dirName, { create: true }); ``` The following asynchronous function uses `resolve()` to find the path to a chosen file, relative to a specified directory handle. ```js async function returnPathDirectories(directoryHandle) { // Get a file handle by showing a file picker: const [handle] = await self.showOpenFilePicker(); if (!handle) { // User cancelled, or otherwise failed to open a file. return; } // Check if handle exists inside our directory handle const relativePaths = await directoryHandle.resolve(handle); if (relativePaths === null) { // Not inside directory handle } else { // relativePaths is an array of names, giving the relative path for (const name of relativePaths) { // log each entry console.log(name); } } } ``` ### Writing to files The following asynchronous function opens the save file picker, which returns a {{domxref('FileSystemFileHandle')}} once a file is selected. A writable stream is then created using the {{domxref('FileSystemFileHandle.createWritable()')}} method. A user defined {{domxref('Blob')}} is then written to the stream which is subsequently closed. ```js async function saveFile() { // create a new handle const newHandle = await window.showSaveFilePicker(); // create a FileSystemWritableFileStream to write to const writableStream = await newHandle.createWritable(); // write our file await writableStream.write(imgBlob); // close the file and write the contents to disk. await writableStream.close(); } ``` The following show different examples of options that can be passed into the `write()` method. ```js // just pass in the data (no options) writableStream.write(data); // writes the data to the stream from the determined position writableStream.write({ type: "write", position, data }); // updates the current file cursor offset to the position specified writableStream.write({ type: "seek", position }); // resizes the file to be size bytes long writableStream.write({ type: "truncate", size }); ``` ### Synchronously reading and writing files in OPFS This example synchronously reads and writes a file to the [origin private file system](#origin_private_file_system). The following asynchronous event handler function is contained inside a Web Worker. On receiving a message from the main thread it: - Creates a synchronous file access handle. - Gets the size of the file and creates an {{jsxref("ArrayBuffer")}} to contain it. - Reads the file contents into the buffer. - Encodes the message and writes it to the end of the file. - Persists the changes to disk and closes the access handle. ```js onmessage = async (e) => { // retrieve message sent to work from main script const message = e.data; // Get handle to draft file in OPFS const root = await navigator.storage.getDirectory(); const draftHandle = await root.getFileHandle("draft.txt", { create: true }); // Get sync access handle const accessHandle = await draftHandle.createSyncAccessHandle(); // Get size of the file. const fileSize = accessHandle.getSize(); // Read file content to a buffer. const buffer = new DataView(new ArrayBuffer(fileSize)); const readBuffer = accessHandle.read(buffer, { at: 0 }); // Write the message to the end of the file. const encoder = new TextEncoder(); const encodedMessage = encoder.encode(message); const writeBuffer = accessHandle.write(encodedMessage, { at: readBuffer }); // Persist changes to disk. accessHandle.flush(); // Always close FileSystemSyncAccessHandle if done. accessHandle.close(); }; ``` > **Note:** In earlier versions of the spec, {{domxref("FileSystemSyncAccessHandle.close()", "close()")}}, {{domxref("FileSystemSyncAccessHandle.flush()", "flush()")}}, {{domxref("FileSystemSyncAccessHandle.getSize()", "getSize()")}}, and {{domxref("FileSystemSyncAccessHandle.truncate()", "truncate()")}} were unergonomically specified as asynchronous methods. This has now been [amended](https://github.com/whatwg/fs/issues/7), but some browsers still support the asynchronous versions. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [The File System Access API: simplifying access to local files](https://developer.chrome.com/docs/capabilities/web-apis/file-system-access) on web.dev - [The origin private file system](https://web.dev/articles/origin-private-file-system) on web.dev
0
data/mdn-content/files/en-us/web/api/file_system_api
data/mdn-content/files/en-us/web/api/file_system_api/origin_private_file_system/index.md
--- title: Origin private file system slug: Web/API/File_System_API/Origin_private_file_system page-type: guide browser-compat: api.StorageManager.getDirectory --- {{securecontext_header}}{{DefaultAPISidebar("File System API")}} The origin private file system (OPFS) is a storage endpoint provided as part of the [File System API](/en-US/docs/Web/API/File_System_API), which is private to the origin of the page and not visible to the user like the regular file system. It provides access to a special kind of file that is highly optimized for performance and offers in-place write access to its content. ## Working with files using the File System Access API The [File System Access API](https://wicg.github.io/file-system-access/), which extends the [File System API](/en-US/docs/Web/API/File_System_API), provides access to files using picker methods. For example: 1. {{domxref("Window.showOpenFilePicker()")}} allows the user to choose a file to access, which results in a {{domxref("FileSystemFileHandle")}} object being returned. 2. {{domxref("FileSystemFileHandle.getFile()")}} is called to get access to the file's contents, the content is modified using {{domxref("FileSystemFileHandle.createWritable()")}} / {{domxref("FileSystemWritableFileStream.write()")}}. 3. {{domxref("FileSystemHandle.requestPermission()", "FileSystemHandle.requestPermission({mode: 'readwrite'})")}} is used to request the user's permission to save the changes. 4. If the user accepts the permission request, the changes are saved back to the original file. This works, but it has some restrictions. These changes are being made to the user-visible file system, so there are a lot of security checks in place (for example, [safe browsing](https://developers.google.com/safe-browsing) in Chrome) to guard against malicious content being written to that file system. These writes are not in-place, and instead use a temporary file. The original is not modified unless it passes all the security checks. As a result, these operations are fairly slow. It is not so noticeable when you are making small text updates, but the performance suffers when making more significant, large-scale file updates such as [SQLite](https://www.sqlite.org/wasm) database modifications. ## How does the OPFS solve such problems? The OPFS offers low-level, byte-by-byte file access, which is private to the origin of the page and not visible to the user. As a result, it doesn't require the same series of security checks and permission grants and is therefore faster than File System Access API calls. It also has a set of synchronous calls available (other File System API calls are asynchronous) that can be run inside web workers only so as not to block the main thread. To summarize how the OPFS differs from the user-visible file system: - The OPFS is subject to [browser storage quota restrictions](/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria), just like any other origin-partitioned storage mechanism (for example {{domxref("IndexedDB API", "IndexedDB API", "", "nocode")}}). You can access the amount of storage space the OPFS is using via {{domxref("StorageManager.estimate()", "navigator.storage.estimate()")}}. - Clearing storage data for the site deletes the OPFS. - Permission prompts and security checks are not required to access files in the OPFS. - Browsers persist the contents of the OPFS to disk somewhere, but you cannot expect to find the created files matched one-to-one. The OPFS is not intended to be visible to the user. ## How do you access the OPFS? To access the OPFS in the first place, you call the {{domxref("StorageManager.getDirectory()", "navigator.storage.getDirectory()")}} method. This returns a reference to a {{domxref("FileSystemDirectoryHandle")}} object that represents the root of the OPFS. ## Manipulating the OPFS from the main thread When accessing the OPFS from the main thread, you will use asynchronous, {{jsxref("Promise")}}-based APIs. You can access file ({{domxref("FileSystemFileHandle")}}) and directory ({{domxref("FileSystemDirectoryHandle")}}) handles by calling {{domxref("FileSystemDirectoryHandle.getFileHandle()")}} and {{domxref("FileSystemDirectoryHandle.getDirectoryHandle()")}} respectively on the {{domxref("FileSystemDirectoryHandle")}} object representing the OPFS root (and child directories, as they are created). > **Note:** Passing `{ create: true }` into the above methods causes the file or folder to be created if it doesn't exist. ```js // Create a hierarchy of files and folders const fileHandle = await opfsRoot.getFileHandle("my first file", { create: true, }); const directoryHandle = await opfsRoot.getDirectoryHandle("my first folder", { create: true, }); const nestedFileHandle = await directoryHandle.getFileHandle( "my first nested file", { create: true }, ); const nestedDirectoryHandle = await directoryHandle.getDirectoryHandle( "my first nested folder", { create: true }, ); // Access existing files and folders via their names const existingFileHandle = await opfsRoot.getFileHandle("my first file"); const existingDirectoryHandle = await opfsRoot.getDirectoryHandle("my first folder"); ``` ### Reading a file 1. Make a {{domxref("FileSystemDirectoryHandle.getFileHandle()")}} call to return a {{domxref("FileSystemFileHandle")}} object. 2. Call the {{domxref("FileSystemFileHandle.getFile()")}} object to return a {{domxref("File")}} object. This is a specialized type of {{domxref("Blob")}}, and as such can be manipulated just like any other `Blob`. For example, you could access the text content directly via {{domxref("Blob.text()")}}. ### Writing a file 1. Make a {{domxref("FileSystemDirectoryHandle.getFileHandle()")}} call to return a {{domxref("FileSystemFileHandle")}} object. 2. Call {{domxref("FileSystemFileHandle.createWritable()")}} to return a {{domxref("FileSystemWritableFileStream")}} object, which is a specialized type of {{domxref("WritableStream")}}. 3. Write contents to it using a {{domxref("FileSystemWritableFilestream.write()")}} call. 4. Close the stream using {{domxref("WritableStream.close()")}}. ### Deleting a file or folder You can call {{domxref("FileSystemDirectoryHandle.removeEntry()")}} on the parent directory, passing it the name of the item you want to remove: ```js directoryHandle.removeEntry("my first nested file"); ``` You can also call {{domxref("FileSystemHandle.remove()")}} on the {{domxref("FileSystemFileHandle")}} or {{domxref("FileSystemDirectoryHandle")}} representing the item you want to remove. To delete a folder including all subfolders, pass the `{ recursive: true }` option. ```js await fileHandle.remove(); await directoryHandle.remove({ recursive: true }); ``` The following provides a quick way to clear the entire OPFS: ```js await (await navigator.storage.getDirectory()).remove({ recursive: true }); ``` ### Listing the contents of a folder {{domxref("FileSystemDirectoryHandle")}} is an [asynchronous iterator](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). As such, you can iterate over it with a [`for await…of`](/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) loop and standard methods such as [`entries()`](/en-US/docs/Web/API/FileSystemDirectoryHandle/entries), [`values()`](/en-US/docs/Web/API/FileSystemDirectoryHandle/entries), and [`keys()`](/en-US/docs/Web/API/FileSystemDirectoryHandle/entries). For example: ```js for await (let [name, handle] of directoryHandle) { } for await (let [name, handle] of directoryHandle.entries()) { } for await (let handle of directoryHandle.values()) { } for await (let name of directoryHandle.keys()) { } ``` ## Manipulating the OPFS from a web worker Web Workers don't block the main thread, which means you can use the synchronous file access APIs in this context. Synchronous APIs are faster as they avoid having to deal with promises. You can synchronously access a file by calling {{domxref("FileSystemFileHandle.createSyncAccessHandle()")}} on a regular {{domxref("FileSystemFileHandle")}}: > **Note:** Despite having "Sync" in its name, the `createSyncAccessHandle()` method itself is asynchronous. ```js const opfsRoot = await navigator.storage.getDirectory(); const fileHandle = await opfsRoot.getFileHandle("my highspeed file.txt", { create: true, }); const syncAccessHandle = await fileHandle.createSyncAccessHandle(); ``` There are a number of _synchronous_ methods available on the returned {{domxref("FileSystemSyncAccessHandle")}}: - {{domxref("FileSystemSyncAccessHandle.getSize", "getSize()")}}: Returns the size of the file in bytes. - {{domxref("FileSystemSyncAccessHandle.write", "write()")}}: Writes the content of a buffer into the file, optionally at a given offset, and returns the number of written bytes. Checking the returned number of written bytes allows callers to detect and handle errors and partial writes. - {{domxref("FileSystemSyncAccessHandle.read", "read()")}}: Reads the contents of the file into a buffer, optionally at a given offset. - {{domxref("FileSystemSyncAccessHandle.truncate", "truncate()")}}: Resizes the file to the given size. - {{domxref("FileSystemSyncAccessHandle.flush", "flush()")}}: Ensures that the file contents contain all the modifications done through `write()`. - {{domxref("FileSystemSyncAccessHandle.close", "close()")}}: Closes the access handle. Here is an example that uses all the methods mentioned above: ```js const opfsRoot = await navigator.storage.getDirectory(); const fileHandle = await opfsRoot.getFileHandle("fast", { create: true }); const accessHandle = await fileHandle.createSyncAccessHandle(); const textEncoder = new TextEncoder(); const textDecoder = new TextDecoder(); // Initialize this variable for the size of the file. let size; // The current size of the file, initially `0`. size = accessHandle.getSize(); // Encode content to write to the file. const content = textEncoder.encode("Some text"); // Write the content at the beginning of the file. accessHandle.write(content, { at: size }); // Flush the changes. accessHandle.flush(); // The current size of the file, now `9` (the length of "Some text"). size = accessHandle.getSize(); // Encode more content to write to the file. const moreContent = textEncoder.encode("More content"); // Write the content at the end of the file. accessHandle.write(moreContent, { at: size }); // Flush the changes. accessHandle.flush(); // The current size of the file, now `21` (the length of // "Some textMore content"). size = accessHandle.getSize(); // Prepare a data view of the length of the file. const dataView = new DataView(new ArrayBuffer(size)); // Read the entire file into the data view. accessHandle.read(dataView); // Logs `"Some textMore content"`. console.log(textDecoder.decode(dataView)); // Read starting at offset 9 into the data view. accessHandle.read(dataView, { at: 9 }); // Logs `"More content"`. console.log(textDecoder.decode(dataView)); // Truncate the file after 4 bytes. accessHandle.truncate(4); ``` ## Browser compatibility {{Compat}} ## See also - [The origin private file system](https://web.dev/articles/origin-private-file-system) on web.dev
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/ext_float_blend/index.md
--- title: EXT_float_blend extension short-title: EXT_float_blend slug: Web/API/EXT_float_blend page-type: webgl-extension browser-compat: api.EXT_float_blend --- {{APIRef("WebGL")}} The [WebGL API](/en-US/docs/Web/API/WebGL_API)'s `EXT_float_blend` extension allows blending and draw buffers with 32-bit floating-point components. WebGL extensions are available using the {{domxref("WebGLRenderingContext.getExtension()")}} method. For more information, see also [Using Extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) in the [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial). > **Note:** This extension is available to both, {{domxref("WebGLRenderingContext", "WebGL1", "", 1)}} and {{domxref("WebGL2RenderingContext", "WebGL2", "", 1)}} contexts. However, to use it, you need to enable the use of 32-bit floating-point draw buffers by enabling the extension {{domxref("WEBGL_color_buffer_float")}} (for WebGL1) or {{domxref("EXT_color_buffer_float")}} (for WebGL2). Doing so automatically enables `EXT_float_blend` as well, if and only if `EXT_float_blend` is also supported. Support for `EXT_color_buffer_float` does not imply support for `EXT_float_blend`. With this extension enabled, calling {{domxref("WebGLRenderingContext.drawArrays", "drawArrays()")}} or {{domxref("WebGLRenderingContext.drawElements", "drawElements()")}} with blending enabled and a draw buffer with 32-bit floating-point components will no longer result in an `INVALID_OPERATION` error. ## Usage notes On devices that support the `EXT_float_blend` extension, it is automatically, implicitly, enabled when any one or more of {{domxref("EXT_color_buffer_float")}}, {{domxref("OES_texture_float")}}, or {{domxref("WEBGL_color_buffer_float")}} are enabled. This ensures that content written before `EXT_float_blend` was exposed by WebGL will function as expected. ## Examples ```js const gl = canvas.getContext("webgl2"); // enable necessary extensions gl.getExtension("EXT_color_buffer_float"); gl.getExtension("EXT_float_blend"); const tex = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, tex); // use floating point format gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, 1, 1, 0, gl.RGBA, gl.FLOAT, null); const fb = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, fb); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0, ); // enable blending gl.enable(gl.BLEND); gl.drawArrays(gl.POINTS, 0, 1); // won't throw gl.INVALID_OPERATION with the extension enabled ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WebGL API](/en-US/docs/Web/API/WebGL_API) - [Using WebGL extensions](/en-US/docs/Web/API/WebGL_API/Using_Extensions) - [WebGL tutorial](/en-US/docs/Web/API/WebGL_API/Tutorial) - {{domxref("WebGLRenderingContext.getExtension()")}} - {{domxref("EXT_color_buffer_float")}} - {{domxref("WEBGL_color_buffer_float")}} - {{domxref("WebGLRenderingContext.drawArrays()")}} - {{domxref("WebGLRenderingContext.drawElements()")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/navigationpreloadmanager/index.md
--- title: NavigationPreloadManager slug: Web/API/NavigationPreloadManager page-type: web-api-interface browser-compat: api.NavigationPreloadManager --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`NavigationPreloadManager`** interface of the [Service Worker API](/en-US/docs/Web/API/Service_Worker_API) provides methods for managing the preloading of resources in parallel with service worker bootup. If supported, an object of this type is returned by {{domxref("ServiceWorkerRegistration.navigationPreload")}}. The result of a preload fetch request is waited on using the promise returned by {{domxref("FetchEvent.preloadResponse")}}. ## Instance methods - {{domxref("NavigationPreloadManager.enable()")}} - : Enables navigation preloading, returning a {{jsxref("Promise")}} that resolves with {{jsxref('undefined')}}. - {{domxref("NavigationPreloadManager.disable()")}} - : Disables navigation preloading, returning a {{jsxref("Promise")}} that resolves with {{jsxref('undefined')}}. - {{domxref("NavigationPreloadManager.setHeaderValue()")}} - : Sets the value of the {{HTTPHeader("Service-Worker-Navigation-Preload")}} HTTP header sent in preloading requests and returns an empty {{jsxref("Promise")}}. - {{domxref("NavigationPreloadManager.getState()")}} - : Returns a {{jsxref("Promise")}} that resolves to an object with properties that indicate whether preloading is enabled, and what value will be sent in the {{HTTPHeader("Service-Worker-Navigation-Preload")}} HTTP header in preloading requests. ## Description Service workers handle {{domxref("fetch()")}} events on behalf of a site, for pages within a given scope. When a user navigates to a page that uses a service worker, the browser boots up the worker (if it isn't already running), then sends it a fetch event and waits for the result. On receiving an event, the worker returns the resource from a cache if it is present, or otherwise fetches the resource from the remote server (storing a copy for returning in future requests). A service worker cannot process events from the browser until it has booted. This is unavoidable, but usually doesn't have much impact. Service workers are often already started (they remain active for some time after processing other requests). Even if a service worker does have to boot, much of the time it may be returning values from a cache, which is very fast. However, in those cases where a worker has to boot before it can start fetching a remote resource, then the delay can be significant. The {{domxref("NavigationPreloadManager")}} provides a mechanism to allow fetching of the resources to run in parallel with service worker boot, so that by the time the worker is able to handle the fetch request from the browser, the resource may already have been fully or partially downloaded. This makes the case where the worker has to start up "no worse" than when the worker is already started, and in some cases better. The preload manager sends the {{HTTPHeader("Service-Worker-Navigation-Preload")}} HTTP header with preload requests, allowing responses to be customized for preload requests. This might be used, for example, to reduce the data sent to just part of the original page, or to customize the response based on the user's log-in state. ## Examples The examples here are from [Speed up Service Worker with Navigation Preloads](https://developer.chrome.com/blog/navigation-preload/) (developer.chrome.com). ### Feature detection and enabling navigation preloading Below we enable navigation preloading in the service worker's `activate` event handler, after first using {{domxref("ServiceWorkerRegistration.navigationPreload")}} to determine if the feature is supported (this returns either the `NavigationPreloadManager` for the service worker or `undefined` if the feature is not supported). ```js addEventListener("activate", (event) => { event.waitUntil( (async () => { if (self.registration.navigationPreload) { // Enable navigation preloads! await self.registration.navigationPreload.enable(); } })(), ); }); ``` ### Using a preloaded response The following code shows a service worker fetch event handler that uses a preloaded response ({{domxref("FetchEvent.preloadResponse")}}). The `fetch` event handler calls {{domxref("FetchEvent.respondWith", "FetchEvent.respondWith()")}} to pass a promise back to the controlled page. This promise will resolve with the requested resource, which may be from the cache, a preloaded fetch request, or a new network request. If there is a matching URL request in the {{domxref("Cache")}} object, then the code returns a resolved promise for fetching the response from the cache. If no match is found in the cache, the code returns the resolved preloaded response ({{domxref("FetchEvent.preloadResponse")}}). If there is no matching cache entry or preloaded response, the code starts a new fetch operation from the network and returns the (unresolved) promise for that fetch operation. ```js addEventListener("fetch", (event) => { event.respondWith( (async () => { // Respond from the cache if we can const cachedResponse = await caches.match(event.request); if (cachedResponse) return cachedResponse; // Else, use the preloaded response, if it's there const response = await event.preloadResponse; if (response) return response; // Else try the network. return fetch(event.request); })(), ); }); ``` ### Custom responses The browser sends the HTTP header {{HTTPHeader("Service-Worker-Navigation-Preload")}} with preload requests, with a default directive value of `true`. This allows servers to differentiate between normal and preload fetch requests, and to send different responses in each case if required. > **Note:** If the response from preload and normal fetch operations can be different, then the server must set `Vary: Service-Worker-Navigation-Preload` to ensure that the different responses are cached. The header value can be changed to any other string value using {{domxref("NavigationPreloadManager.setHeaderValue()")}} in order to provide additional context for the prefetch operation. For example, you might set the value to the ID of your most recently cached resource, so that the server won't return any resources unless they are actually needed. Similarly, you could configure the returned information based on authentication status instead of using cookies. The code below shows how to set the value of the header directive to some variable `newValue`. ```js navigator.serviceWorker.ready .then((registration) => registration.navigationPreload.setHeaderValue(newValue), ) .then(() => { console.log("Done!"); }); ``` [Speed up Service Worker with Navigation Preloads > Custom responses for preloads](https://developer.chrome.com/blog/navigation-preload/) provides a more complete example of a site where the response for an article web page is constructed from a cached header and footer, so that only the article content is returned for a prefetch. ### Getting the state You can use {{domxref("NavigationPreloadManager.getState()")}} to check whether navigation preloading is enabled and to determine what directive value is sent with the {{HTTPHeader("Service-Worker-Navigation-Preload")}} HTTP header for preload requests. The code below shows how to get the promise that resolves to a `state` object and log the result. ```js navigator.serviceWorker.ready .then((registration) => registration.navigationPreload.getState()) .then((state) => { console.log(state.enabled); // boolean console.log(state.headerValue); // string }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Speed up Service Worker with Navigation Preloads](https://developer.chrome.com/blog/navigation-preload/) (developer.chrome.com)
0
data/mdn-content/files/en-us/web/api/navigationpreloadmanager
data/mdn-content/files/en-us/web/api/navigationpreloadmanager/enable/index.md
--- title: "NavigationPreloadManager: enable() method" short-title: enable() slug: Web/API/NavigationPreloadManager/enable page-type: web-api-instance-method browser-compat: api.NavigationPreloadManager.enable --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`enable()`** method of the {{domxref("NavigationPreloadManager")}} interface is used to enable preloading of resources managed by the service worker. It returns a promise that resolves with `undefined`. The method should be called in the service worker's `activate` event handler, which ensures it is called before any `fetch` event handler can fire. ## Syntax ```js-nolint enable() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with {{jsxref('undefined')}}. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : There is no active worker associated with the registration to which this {{domxref("NavigationPreloadManager")}} belongs. ## Examples The code below shows how to enable preloading, after first using {{domxref("ServiceWorkerRegistration.navigationPreload")}} to test that it is supported. ```js addEventListener("activate", (event) => { event.waitUntil( (async () => { if (self.registration.navigationPreload) { // Enable navigation preloads! await self.registration.navigationPreload.enable(); } })(), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also {{domxref("NavigationPreloadManager.disable()")}}
0
data/mdn-content/files/en-us/web/api/navigationpreloadmanager
data/mdn-content/files/en-us/web/api/navigationpreloadmanager/setheadervalue/index.md
--- title: "NavigationPreloadManager: setHeaderValue() method" short-title: setHeaderValue() slug: Web/API/NavigationPreloadManager/setHeaderValue page-type: web-api-instance-method browser-compat: api.NavigationPreloadManager.setHeaderValue --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`setHeaderValue()`** method of the {{domxref("NavigationPreloadManager")}} interface sets the value of the {{HTTPHeader("Service-Worker-Navigation-Preload")}} header that will be sent with requests resulting from a {{domxref("fetch()")}} operation made during service worker navigation preloading. It returns an empty {{jsxref("Promise")}} that resolves with `undefined`. The presence of the {{HTTPHeader("Service-Worker-Navigation-Preload")}} header in preloading requests allows servers to configure the returned resource differently for preloading fetch requests than from normal fetch requests. The default directive is set to `true`: this method allows the possibility of configuring multiple different responses to preload requests. > **Note:** If a different response may result from setting this header, the server must set `Vary: Service-Worker-Navigation-Preload` to ensure that the different responses are cached. ## Syntax ```js-nolint setHeaderValue(value) ``` ### Parameters - `value` - : An arbitrary string value, which the target server uses to determine what should returned for the requested resource. ### Return value A {{jsxref("Promise")}} that resolves with {{jsxref('undefined')}}. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : There is no active worker associated with the registration to which this {{domxref("NavigationPreloadManager")}} belongs. ## Examples The code below demonstrates how the value might be set. ```js navigator.serviceWorker.ready .then((registration) => registration.navigationPreload.setHeaderValue(newValue), ) .then(() => console.log("Done!")) .catch((e) => console.error(`NavigationPreloadManager not supported: ${e.message}`), ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/navigationpreloadmanager
data/mdn-content/files/en-us/web/api/navigationpreloadmanager/disable/index.md
--- title: "NavigationPreloadManager: disable() method" short-title: disable() slug: Web/API/NavigationPreloadManager/disable page-type: web-api-instance-method browser-compat: api.NavigationPreloadManager.disable --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`disable()`** method of the {{domxref("NavigationPreloadManager")}} interface halts the automatic preloading of service-worker-managed resources previously started using {{domxref("NavigationPreloadManager.enable()","enable()")}} It returns a promise that resolves with `undefined`. The method may be called in the service worker's `activate` event handler (before the `fetch` event handler can be called). ## Syntax ```js-nolint disable() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with {{jsxref('undefined')}}. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : There is no active worker associated with the registration to which this {{domxref("NavigationPreloadManager")}} belongs. ## Examples The code below shows how to disable preloading, after first using {{domxref("ServiceWorkerRegistration.navigationPreload")}} to test that it is supported. ```js addEventListener("activate", (event) => { event.waitUntil( (async () => { if (self.registration.navigationPreload) { // Disable navigation preloads! await self.registration.navigationPreload.disable(); } })(), ); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also {{domxref("NavigationPreloadManager.enable()")}}
0
data/mdn-content/files/en-us/web/api/navigationpreloadmanager
data/mdn-content/files/en-us/web/api/navigationpreloadmanager/getstate/index.md
--- title: "NavigationPreloadManager: getState() method" short-title: getState() slug: Web/API/NavigationPreloadManager/getState page-type: web-api-instance-method browser-compat: api.NavigationPreloadManager.getState --- {{APIRef("Service Workers API")}}{{SecureContext_Header}} The **`getState()`** method of the {{domxref("NavigationPreloadManager")}} interface returns a {{jsxref("Promise")}} that resolves to an object with properties that indicate whether preload is enabled and what value will be sent in the {{HTTPHeader("Service-Worker-Navigation-Preload")}} HTTP header. ## Syntax ```js-nolint getState() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that resolves with an object that has the following properties: - `enabled` - : `true` if preloading is enabled, and `false` otherwise. - `headerValue` - : A string containing the value that will be sent in the `Service-Worker-Navigation-Preload` HTTP header following a preloading {{domxref("fetch()")}}. This defaults to `true` unless the value was changed using {{domxref("NavigationPreloadManager.setHeaderValue()")}}. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : There is no active worker associated with the registration to which this {{domxref("NavigationPreloadManager")}} belongs. ## Examples The code below shows a request for the current state, made once the service worker is ready. ```js navigator.serviceWorker.ready .then((registration) => registration.navigationPreload.getState()) .then((state) => { console.log(state.enabled); // boolean console.log(state.headerValue); // string }) .catch((e) => console.error(`NavigationPreloadManager not supported: ${e.message}`), ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/gpucommandbuffer/index.md
--- title: GPUCommandBuffer slug: Web/API/GPUCommandBuffer page-type: web-api-interface status: - experimental browser-compat: api.GPUCommandBuffer --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`GPUCommandBuffer`** interface of the {{domxref("WebGPU API", "WebGPU API", "", "nocode")}} represents a pre-recorded list of GPU commands that can be submitted to a {{domxref("GPUQueue")}} for execution. A `GPUCommandBuffer` is created via the {{domxref("GPUCommandEncoder.finish()")}} method; the GPU commands recorded within are submitted for execution by passing the `GPUCommandBuffer` into the parameter of a {{domxref("GPUQueue.submit()")}} call. > **Note:** Once a `GPUCommandBuffer` object has been submitted, it cannot be used again. {{InheritanceDiagram}} ## Instance properties - {{domxref("GPUCommandBuffer.label", "label")}} {{Experimental_Inline}} - : A string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. ## Examples ```js // ... const commandBuffer = commandEncoder.finish(); device.queue.submit([commandBuffer]); ``` > **Note:** Study the [WebGPU samples](https://webgpu.github.io/webgpu-samples/) to find complete examples. ## 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/gpucommandbuffer
data/mdn-content/files/en-us/web/api/gpucommandbuffer/label/index.md
--- title: "GPUCommandBuffer: label property" short-title: label slug: Web/API/GPUCommandBuffer/label page-type: web-api-instance-property status: - experimental browser-compat: api.GPUCommandBuffer.label --- {{APIRef("WebGPU API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`label`** read-only property of the {{domxref("GPUCommandBuffer")}} interface is a string providing a label that can be used to identify the object, for example in {{domxref("GPUError")}} messages or console warnings. This can be set by providing a `label` property in the descriptor object passed into the originating {{domxref("GPUCommandEncoder.finish()")}} call, or you can get and set it directly on the `GPUCommandBuffer` object. ## Value A string. If no label value has previously been set, getting the label returns an empty string. ## Examples Setting and getting a label via `GPUCommandBuffer.label`: ```js const commandBuffer = commandEncoder.finish(); commandBuffer.label = "mycommandbuffer"; console.log(commandBuffer.label); // "mycommandbuffer"; ``` Setting a label via the originating {{domxref("GPUCommandEncoder.finish()")}} call, and then getting it via `GPUCommandBuffer.label`: ```js const commandBuffer = commandEncoder.finish({ label: "mycommandbuffer", }); console.log(commandBuffer.label); // "mycommandbuffer"; ``` ## 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/mediastreamaudiosourcenode/index.md
--- title: MediaStreamAudioSourceNode slug: Web/API/MediaStreamAudioSourceNode page-type: web-api-interface browser-compat: api.MediaStreamAudioSourceNode --- {{APIRef("Web Audio API")}} The **`MediaStreamAudioSourceNode`** interface is a type of {{domxref("AudioNode")}} which operates as an audio source whose media is received from a {{domxref("MediaStream")}} obtained using the WebRTC or Media Capture and Streams APIs. This media could be from a microphone (through {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}}) or from a remote peer on a WebRTC call (using the {{domxref("RTCPeerConnection")}}'s audio tracks). A `MediaStreamAudioSourceNode` has no inputs and exactly one output, and is created using the {{domxref("AudioContext.createMediaStreamSource()")}} method. The `MediaStreamAudioSourceNode` takes the audio from the _first_ {{domxref("MediaStreamTrack")}} whose {{domxref("MediaStreamTrack.kind", "kind")}} attribute's value is `audio`. See [Track ordering](#track_ordering) for more information about the order of tracks. The number of channels output by the node matches the number of tracks found in the selected audio track. {{InheritanceDiagram}} <table class="properties"> <tbody> <tr> <th scope="row">Number of inputs</th> <td><code>0</code></td> </tr> <tr> <th scope="row">Number of outputs</th> <td><code>1</code></td> </tr> <tr> <th scope="row">Channel count</th> <td> 2 (but note that {{domxref("AudioNode.channelCount")}} is only used for up-mixing and down-mixing {{domxref("AudioNode")}} inputs, and {{domxref("MediaStreamAudioSourceNode")}} doesn't have any input) </td> </tr> </tbody> </table> ## Constructor - {{domxref("MediaStreamAudioSourceNode.MediaStreamAudioSourceNode", "new MediaStreamAudioSourceNode()")}} - : Creates a new `MediaStreamAudioSourceNode` object instance with the specified options. ## Instance properties _In addition to the following properties, `MediaStreamAudioSourceNode` inherits the properties of its parent, {{domxref("AudioNode")}}._ - {{domxref("MediaStreamAudioSourceNode.mediaStream", "mediaStream")}} {{ReadOnlyInline}} - : The {{domxref("MediaStream")}} used when constructing this `MediaStreamAudioSourceNode`. ## Instance methods _Inherits methods from its parent, {{domxref("AudioNode")}}_. ## Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the stream specified by the `mediaStream` parameter does not contain any audio tracks. ## Usage notes ### Track ordering For the purposes of the `MediaStreamTrackAudioSourceNode` interface, the order of the audio tracks on the stream is determined by taking the tracks whose {{domxref("MediaStreamTrack.kind", "kind")}} is `audio`, then sorting the tracks by their {{domxref("MediaStreamTrack.id", "id")}} property's values, in Unicode code point order (essentially, in alphabetical or lexicographical order, for IDs which are simple alphanumeric strings). The **first** track, then, is the track whose `id` comes first when the tracks' IDs are all sorted by Unicode code point. However, it's important to note that the rule establishing this ordering was added long after this interface was first introduced into the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API). As such, you can't easily rely on the order matching between any two browsers or browser versions. The {{domxref("MediaStreamTrackAudioSourceNode")}} interface is similar to `MediaStreamAudioSourceNode`, but avoids this problem by letting you specify which track you want to use. ## Example See [`AudioContext.createMediaStreamSource()`](/en-US/docs/Web/API/AudioContext/createMediaStreamSource#examples) for example code that uses this object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API) - [WebRTC API](/en-US/docs/Web/API/WebRTC_API) - [Media Capture and Streams API (Media Streams)](/en-US/docs/Web/API/Media_Capture_and_Streams_API) - {{domxref("MediaStreamTrackAudioSourceNode")}}
0
data/mdn-content/files/en-us/web/api/mediastreamaudiosourcenode
data/mdn-content/files/en-us/web/api/mediastreamaudiosourcenode/mediastream/index.md
--- title: "MediaStreamAudioSourceNode: mediaStream property" short-title: mediaStream slug: Web/API/MediaStreamAudioSourceNode/mediaStream page-type: web-api-instance-property browser-compat: api.MediaStreamAudioSourceNode.mediaStream --- {{APIRef("Web Audio API")}} The {{domxref("MediaStreamAudioSourceNode")}} interface's read-only **`mediaStream`** property indicates the {{domxref("MediaStream")}} that contains the audio track from which the node is receiving audio. This stream was specified when the node was first created, either using the {{domxref("MediaStreamAudioSourceNode.MediaStreamAudioSourceNode", "MediaStreamAudioSourceNode()")}} constructor or the {{domxref("AudioContext.createMediaStreamSource()")}} method. ## Value A {{domxref("MediaStream")}} representing the stream which contains the {{domxref("MediaStreamTrack")}} serving as the source of audio for the node. The {{Glossary("user agent")}} uses the first audio track it finds on the specified stream as the audio source for this node. However, there is no way to be certain which track that will be on multi-track streams. If the specific track matters to you, or you need to have access to the track itself, you should use a {{domxref("MediaStreamTrackAudioSourceNode")}} instead. ## Examples ```js const audioCtx = new window.AudioContext(); let options = { mediaStream: stream, }; let source = new MediaStreamAudioSourceNode(audioCtx, options); console.log(source.mediaStream); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/mediastreamaudiosourcenode
data/mdn-content/files/en-us/web/api/mediastreamaudiosourcenode/mediastreamaudiosourcenode/index.md
--- title: "MediaStreamAudioSourceNode: MediaStreamAudioSourceNode() constructor" short-title: MediaStreamAudioSourceNode() slug: Web/API/MediaStreamAudioSourceNode/MediaStreamAudioSourceNode page-type: web-api-constructor browser-compat: api.MediaStreamAudioSourceNode.MediaStreamAudioSourceNode --- {{APIRef("Web Audio API")}} The [Web Audio API](/en-US/docs/Web/API/Web_Audio_API)'s **`MediaStreamAudioSourceNode()`** constructor creates and returns a new {{domxref("MediaStreamAudioSourceNode")}} object which uses the first audio track of a given {{domxref("MediaStream")}} as its source. > **Note:** Another way to create a > `MediaStreamAudioSourceNode` is to call > the {{domxref("AudioContext.createMediaStreamSource()")}} method, specifying the stream > from which you want to obtain audio. ## Syntax ```js-nolint new MediaStreamAudioSourceNode(context, options) ``` ### Parameters - `context` - : An {{domxref("AudioContext")}} representing the audio context you want the node to be associated with. - `options` - : An object defining the properties you want the `MediaStreamAudioSourceNode` to have: - `mediaStream` - : A required property which specifies the {{domxref("MediaStream")}} from which to obtain audio for the node. ### Return value A new {{domxref("MediaStreamAudioSourceNode")}} object representing the audio node whose media is obtained from the specified source stream. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the specified {{domxref("MediaStream")}} does not contain any audio tracks. ## Examples This example uses {{domxref("MediaDevices.getUserMedia", "getUserMedia()")}} to obtain access to the user's camera, then creates a new {{domxref("MediaStreamAudioSourceNode")}} from its {{domxref("MediaStream")}}. ```js // define variables const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // getUserMedia block - grab stream // put it into a MediaStreamAudioSourceNode if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices .getUserMedia( // constraints: audio and video for this app { audio: true, video: false, }, ) .then((stream) => { const options = { mediaStream: stream, }; const source = new MediaStreamAudioSourceNode(audioCtx, options); source.connect(audioCtx.destination); }) .catch((err) => { console.error(`The following gUM error occurred: ${err}`); }); } else { console.log("new getUserMedia not supported on your browser!"); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/view_transitions_api/index.md
--- title: View Transitions API slug: Web/API/View_Transitions_API page-type: web-api-overview status: - experimental browser-compat: api.Document.startViewTransition --- {{SeeCompatTable}}{{DefaultAPISidebar("View Transitions API")}} The **View Transitions API** provides a mechanism for easily creating animated transitions between different DOM states while also updating the DOM contents in a single step. ## Concepts and usage View transitions are a popular design choice for reducing users' cognitive load, helping them stay in context, and reducing perceived loading latency as they move between states or views of an application. However, creating view transitions on the web has historically been difficult. Transitions between states in single-page apps (SPAs) tend to involve writing significant CSS and JavaScript to: - Handle the loading and positioning of the old and new content. - Animate the old and new states to create the transition. - Stop accidental user interactions with the old content from causing problems. - Remove the old content once the transition is complete. Accessibility issues like loss of reading position, focus confusion, and strange live region announcement behavior can also result from having the new and old content both present in the DOM at once. In addition, cross-document view transitions (i.e. across different pages in regular, non-SPA websites) are impossible. The View Transitions API provides a much easier way of handling the required DOM changes and transition animations. > **Note:** The View Transitions API doesn't currently enable cross-document view transitions, but this is planned for a future level of the spec and is actively being worked on. ### Creating a basic view transition As an example, an SPA may include functionality to fetch new content and update the DOM in response to an event of some kind, such as a navigation link being clicked or an update being pushed from the server. In our [Basic View Transitions demo](https://mdn.github.io/dom-examples/view-transitions/) we've simplified this to a `displayNewImage()` function that shows a new full-size image based on the thumbnail that was clicked. We've encapsulated this inside an `updateView()` function that only calls the View Transition API if the browser supports it: ```js function updateView(event) { // Handle the difference in whether the event is fired on the <a> or the <img> const targetIdentifier = event.target.firstChild || event.target; const displayNewImage = () => { const mainSrc = `${targetIdentifier.src.split("_th.jpg")[0]}.jpg`; galleryImg.src = mainSrc; galleryCaption.textContent = targetIdentifier.alt; }; // Fallback for browsers that don't support View Transitions: if (!document.startViewTransition) { displayNewImage(); return; } // With View Transitions: const transition = document.startViewTransition(() => displayNewImage()); } ``` This code is enough to handle the transition between displayed images. Supporting browsers will show the change from old to new images and captions as a smooth cross-fade (the default view transition). It will still work in non-supporting browsers but without the nice animation. It is also worth mentioning that `startViewTransition()` returns a {{domxref("ViewTransition")}} instance, which includes several promises, allowing you to run code in response to different parts of the view transition process being reached. ### The view transition process Let's walk through how this works: 1. When {{domxref("Document.startViewTransition()", "document.startViewTransition()")}} is called, the API takes a screenshot of the current page. 2. Next, the callback passed to `startViewTransition()` is invoked, in this case `displayNewImage`, which causes the DOM to change. When the callback has run successfully, the {{domxref("ViewTransition.updateCallbackDone")}} promise fulfills, allowing you to respond to the DOM updating. 3. The API captures the new state of the page as a live representation. 4. The API constructs a pseudo-element tree with the following structure: ```plain ::view-transition └─ ::view-transition-group(root) └─ ::view-transition-image-pair(root) β”œβ”€ ::view-transition-old(root) └─ ::view-transition-new(root) ``` - {{cssxref("::view-transition")}} is the root of view transitions overlay, which contains all view transitions and sits over the top of all other page content. - {{cssxref("::view-transition-old")}} is the screenshot of the old page view, and {{cssxref("::view-transition-new")}} is the live representation of the new page view. Both of these render as replaced content, in the same manner as an {{htmlelement("img")}} or {{htmlelement("video")}}, meaning that they can be styled with handy properties like {{cssxref("object-fit")}} and {{cssxref("object-position")}}. When the transition animation is about to run, the {{domxref("ViewTransition.ready")}} promise fulfills, allowing you to respond by running a custom JavaScript animation instead of the default, for example. 5. The old page view animates from {{cssxref("opacity")}} 1 to 0, while the new view animates from `opacity` 0 to 1, which is what creates the default cross-fade. 6. When the transition animation has reached its end state, the {{domxref("ViewTransition.finished")}} promise fulfills, allowing you to respond. ### Different transitions for different elements At the moment, all of the different elements that change when the DOM updates are transitioned using the same animation. If you want different elements to animate differently from the default "root" animation, you can separate them out using the {{cssxref("view-transition-name")}} property. For example: ```css figcaption { view-transition-name: figure-caption; } ``` We've given the {{htmlelement("figcaption")}} element a `view-transition-name` of `figure-caption` to separate it from the rest of the page in terms of view transitions. With this CSS applied, the pseudo-element tree will now look like this: ```plain ::view-transition β”œβ”€ ::view-transition-group(root) β”‚ └─ ::view-transition-image-pair(root) β”‚ β”œβ”€ ::view-transition-old(root) β”‚ └─ ::view-transition-new(root) └─ ::view-transition-group(figure-caption) └─ ::view-transition-image-pair(figure-caption) β”œβ”€ ::view-transition-old(figure-caption) └─ ::view-transition-new(figure-caption) ``` The existence of the second set of pseudo-elements allows separate view transition styling to be applied just to the `<figcaption>`. The different old and new page view captures are handled completely separate from one another. The value of `view-transition-name` can be anything you want except for `none` β€” the `none` value specifically means that the element will not participate in a view transition. > **Note:** `view-transition-name` must be unique. If two rendered elements have the same `view-transition-name` at the same time, {{domxref("ViewTransition.ready")}} will reject and the transition will be skipped. ### Customizing your animations The View Transitions pseudo-elements have default [CSS Animations](/en-US/docs/Web/CSS/CSS_animations) applied (which are detailed in their [reference pages](#css_additions)). Notably, transitions for `height`, `width`, `position`, and `transform` do not use the smooth cross-fade animation. Instead, height and width transitions apply a smooth scaling animation. Meanwhile, position and transform transitions apply smooth movement animations to the element. You can modify the default animation in any way you want using regular CSS. For example, to change the speed of it: ```css ::view-transition-old(root), ::view-transition-new(root) { animation-duration: 0.5s; } ``` Let's look at something more interesting β€” a custom animation for the `<figcaption>`: ```css @keyframes grow-x { from { transform: scaleX(0); } to { transform: scaleX(1); } } @keyframes shrink-x { from { transform: scaleX(1); } to { transform: scaleX(0); } } ::view-transition-old(figure-caption), ::view-transition-new(figure-caption) { height: auto; right: 0; left: auto; transform-origin: right center; } ::view-transition-old(figure-caption) { animation: 0.25s linear both shrink-x; } ::view-transition-new(figure-caption) { animation: 0.25s 0.25s linear both grow-x; } ``` Here we've created a custom CSS animation and applied it to the `::view-transition-old(figure-caption)` and `::view-transition-new(figure-caption)` pseudo-elements. We've also added a number of other styles to both to keep them in the same place and stop the default styling from interfering with our custom animations. Note that we also discovered another transition option that is simpler and produced a nicer result than the above. Our final `<figcaption>` view transition ended up looking like this: ```css figcaption { view-transition-name: figure-caption; } ::view-transition-old(figure-caption), ::view-transition-new(figure-caption) { height: 100%; } ``` This works because, by default, `::view-transition-group` transitions width and height between the old and new views. We just needed to set a fixed `height` on both states to make it work. > **Note:** [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/) contains several other customization examples. ### Controlling animations with JavaScript The {{domxref("Document.startViewTransition()", "document.startViewTransition()")}} method returns a {{domxref("ViewTransition")}} object instance, which contains several promise members allowing you to run JavaScript in response to different states of the transition being reached. For example, {{domxref("ViewTransition.ready")}} fulfills once the pseudo-element tree is created and the animation is about to start, whereas {{domxref("ViewTransition.finished")}} fulfills once the animation is finished, and the new page view is visible and interactive to the user. For example, the following JavaScript could be used to create a circular reveal view transition emanating from the position of the user's cursor on click, with animation provided by the {{domxref("Web Animations API", "Web Animations API", "", "nocode")}}. ```js // Store the last click event let lastClick; addEventListener("click", (event) => (lastClick = event)); function spaNavigate(data) { // Fallback for browsers that don’t support this API: if (!document.startViewTransition) { updateTheDOMSomehow(data); return; } // Get the click position, or fallback to the middle of the screen const x = lastClick?.clientX ?? innerWidth / 2; const y = lastClick?.clientY ?? innerHeight / 2; // Get the distance to the furthest corner const endRadius = Math.hypot( Math.max(x, innerWidth - x), Math.max(y, innerHeight - y), ); // Create a transition: const transition = document.startViewTransition(() => { updateTheDOMSomehow(data); }); // Wait for the pseudo-elements to be created: transition.ready.then(() => { // Animate the root’s new view document.documentElement.animate( { clipPath: [ `circle(0 at ${x}px ${y}px)`, `circle(${endRadius}px at ${x}px ${y}px)`, ], }, { duration: 500, easing: "ease-in", // Specify which pseudo-element to animate pseudoElement: "::view-transition-new(root)", }, ); }); } ``` This animation also requires the following CSS, to turn off the default CSS animation and stop the old and new view states from blending in any way (the new state "wipes" right over the top of the old state, rather than transitioning in): ```css ::view-transition-image-pair(root) { isolation: auto; } ::view-transition-old(root), ::view-transition-new(root) { animation: none; mix-blend-mode: normal; display: block; } ``` ## Interfaces - {{domxref("ViewTransition")}} - : Represents a view transition, and provides functionality to react to the transition reaching different states (e.g. ready to run the animation, or animation finished) or skip the transition altogether. ## Extensions to other interfaces - {{domxref("Document.startViewTransition()")}} - : Starts a new view transition and returns a {{domxref("ViewTransition")}} object to represent it. ## CSS additions ### Properties - {{cssxref("view-transition-name")}} - : Provides the selected element with a separate identifying name and causes it to participate in a separate view transition from the root view transition β€” or no view transition if the `none` value is specified. ### Pseudo-elements - {{cssxref("::view-transition")}} - : The root of the view transitions overlay, which contains all view transitions and sits over the top of all other page content. - {{cssxref("::view-transition-group", "::view-transition-group()")}} - : The root of a single view transition. - {{cssxref("::view-transition-image-pair", "::view-transition-image-pair()")}} - : The container for a view transition's old and new views β€” before and after the transition. - {{cssxref("::view-transition-old", "::view-transition-old()")}} - : A static screenshot of the old view, before the transition. - {{cssxref("::view-transition-new", "::view-transition-new()")}} - : A live representation of the new view, after the transition. ## Examples - [Basic View Transitions demo](https://mdn.github.io/dom-examples/view-transitions/): A basic image gallery demo with separate transitions between old and new images, and old and new captions. - [HTTP 203 playlist](https://http203-playlist.netlify.app/): A more sophisticated video player demo app that features a number of different view transitions, many of which are explained in [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Smooth and simple transitions with the View Transitions API](https://developer.chrome.com/docs/web-platform/view-transitions/) - [View Transitions API: Creating Smooth Page Transitions](https://stackdiary.com/view-transitions-api/)
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/htmlvideoelement/index.md
--- title: HTMLVideoElement slug: Web/API/HTMLVideoElement page-type: web-api-interface browser-compat: api.HTMLVideoElement --- {{APIRef("HTML DOM")}} Implemented by the {{HTMLElement("video")}} element, the **`HTMLVideoElement`** interface provides special properties and methods for manipulating video objects. It also inherits properties and methods of {{domxref("HTMLMediaElement")}} and {{domxref("HTMLElement")}}. The list of [supported media formats](/en-US/docs/Web/Media/Formats) varies from one browser to the other. You should either provide your video in a single format that all the relevant browsers supports, or provide multiple video sources in enough different formats that all the browsers you need to support are covered. {{InheritanceDiagram}} ## Instance properties _Inherits properties from its parent interface, {{domxref("HTMLMediaElement")}}, and {{domxref("HTMLElement")}}._ - {{DOMxRef("HTMLVideoElement.disablePictureInPicture")}} - : Indicates if the user agent should suggest the picture-in-picture to users, or not. - {{domxref("HTMLVideoElement.height")}} - : A string that reflects the [`height`](/en-US/docs/Web/HTML/Element/video#height) HTML attribute, which specifies the height of the display area, in CSS pixels. - {{domxref("HTMLVideoElement.poster")}} - : A string that reflects the [`poster`](/en-US/docs/Web/HTML/Element/video#poster) HTML attribute, which specifies an image to show while no video data is available. - {{domxref("HTMLVideoElement.videoHeight")}} {{ReadOnlyInline}} - : Returns an unsigned integer value indicating the intrinsic height of the resource in CSS pixels, or 0 if no media is available yet. - {{domxref("HTMLVideoElement.videoWidth")}} {{ReadOnlyInline}} - : Returns an unsigned integer value indicating the intrinsic width of the resource in CSS pixels, or 0 if no media is available yet. - {{domxref("HTMLVideoElement.width")}} - : A string that reflects the [`width`](/en-US/docs/Web/HTML/Element/video#width) HTML attribute, which specifies the width of the display area, in CSS pixels. ### Gecko-specific properties - {{domxref("HTMLVideoElement.mozParsedFrames")}} {{Non-standard_Inline}} {{ReadOnlyInline}} {{deprecated_inline}} - : Returns an `unsigned long` with the count of video frames that have been parsed from the media resource. - {{domxref("HTMLVideoElement.mozDecodedFrames")}} {{Non-standard_Inline}} {{ReadOnlyInline}} {{deprecated_inline}} - : Returns an `unsigned long` with the count of parsed video frames that have been decoded into images. - {{domxref("HTMLVideoElement.mozPresentedFrames")}} {{Non-standard_Inline}} {{ReadOnlyInline}} {{deprecated_inline}} - : Returns an `unsigned long` with the count of decoded frames that have been presented to the rendering pipeline for painting. - {{domxref("HTMLVideoElement.mozPaintedFrames")}} {{Non-standard_Inline}} {{ReadOnlyInline}} {{deprecated_inline}} - : Returns an `unsigned long` with the count of presented frames which were painted on the screen. - {{domxref("HTMLVideoElement.mozFrameDelay")}} {{Non-standard_Inline}} {{ReadOnlyInline}} {{deprecated_inline}} - : Returns an `double` with the time which the last painted video frame was late by, in seconds. - {{domxref("HTMLVideoElement.mozHasAudio")}} {{Non-standard_Inline}} {{ReadOnlyInline}} {{deprecated_inline}} - : Returns a boolean indicating if there is some audio associated with the video. ## Instance methods _Inherits methods from its parent interface, {{domxref("HTMLMediaElement")}}, and {{domxref("HTMLElement")}}._ - {{DOMxRef("HTMLVideoElement.cancelVideoFrameCallback()")}} - : Cancels a previously-registered video frame callback (see {{DOMxRef("HTMLVideoElement.requestVideoFrameCallback", "requestVideoFrameCallback()")}}). - {{domxref("HTMLVideoElement.getVideoPlaybackQuality()")}} - : Returns a {{domxref("VideoPlaybackQuality")}} object that contains the current playback metrics. This information includes things like the number of dropped or corrupted frames, as well as the total number of frames. - {{DOMxRef("HTMLVideoElement.requestPictureInPicture()")}} - : Requests that the user agent enters the video into picture-in-picture mode. - {{DOMxRef("HTMLVideoElement.requestVideoFrameCallback()")}} - : Registers a callback function that runs when a new video frame is sent to the compositor. This enables developers to perform efficient operations on each video frame. ## Events _Inherits events from its parent interface, {{domxref("HTMLMediaElement")}}, and {{domxref("HTMLElement")}}._ Listen to these events using {{domxref("EventTarget.addEventListener", "addEventListener()")}} or by assigning an event listener to the `oneventname` property of this interface. - {{DOMxRef("HTMLVideoElement.enterpictureinpicture_event", "enterpictureinpicture")}} - : Fired when the `HTMLVideoElement` enters picture-in-picture mode successfully. - {{DOMxRef("HTMLVideoElement.leavepictureinpicture_event", "leavepictureinpicture")}} - : Fired when the `HTMLVideoElement` leaves picture-in-picture mode successfully. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - HTML element implementing this interface: {{HTMLElement("video")}}. - [Supported media formats](/en-US/docs/Web/Media/Formats)
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/videowidth/index.md
--- title: "HTMLVideoElement: videoWidth property" short-title: videoWidth slug: Web/API/HTMLVideoElement/videoWidth page-type: web-api-instance-property browser-compat: api.HTMLVideoElement.videoWidth --- {{APIRef("HTML DOM")}} The {{domxref("HTMLVideoElement")}} interface's read-only **`videoWidth`** property indicates the [intrinsic width](/en-US/docs/Web/API/HTMLVideoElement/videoHeight#about_intrinsic_width_and_height) of the video, expressed in CSS pixels. In simple terms, this is the width of the media in its natural size. See [`HTMLVideoElement.videoHeight` > About intrinsic width and height](/en-US/docs/Web/API/HTMLVideoElement/videoHeight#about_intrinsic_width_and_height) for more details. ## Value An integer value specifying the intrinsic width of the video in CSS pixels. If the element's {{domxref("HTMLMediaElement.readyState", "readyState")}} is `HTMLMediaElement.HAVE_NOTHING`, then the value of this property is 0, because neither video nor poster frame size information is yet available. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/requestvideoframecallback/index.md
--- title: "HTMLVideoElement: requestVideoFrameCallback() method" short-title: requestVideoFrameCallback() slug: Web/API/HTMLVideoElement/requestVideoFrameCallback page-type: web-api-instance-method browser-compat: api.HTMLVideoElement.requestVideoFrameCallback --- {{APIRef("HTML DOM")}} The **`requestVideoFrameCallback()`** method of the {{domxref("HTMLVideoElement")}} interface registers a callback function that runs when a new video frame is sent to the compositor. This enables developers to perform efficient operations on each video frame. ## Description Typical use cases for `requestVideoFrameCallback()` include video processing and painting to a canvas, video analysis, and synchronization with external audio sources. Per-frame processing used to be done in a less efficient or accurate fashion by running operations on the current video display whenever the {{domxref("HTMLMediaElement.timeupdate_event", "timeupdate")}} event fired. This technique did not provide access to the actual video frames. `requestVideoFrameCallback()` is used in the same way as {{domxref("Window.requestAnimationFrame()")}}. You use it to run a callback function that performs some operation when the next video frame is sent to the compositor. The callback finishes by calling `requestVideoFrameCallback()` again to run the callback when the next video frame is composited, and so on. However, `requestVideoFrameCallback()` is tailored for video operations in several ways: - `requestVideoFrameCallback()` provides reliable access to each individual video frame. - `requestAnimationFrame()` tries to match the display refresh rate, which is typically 60Hz. `requestVideoFrameCallback()`, on the other hand, tries to match the video frame rate. More specifically, the callback will run at the lower of the video frame rate and the browser paint refresh rate. For example, a video with a frame rate of 25fps playing in a browser that paints at 60Hz would fire callbacks at a rate of 25Hz. A video with a frame rate of 120fps running in the same 60Hz browser would fire callbacks at 60Hz. - `requestVideoFrameCallback()` makes useful video metadata available in the callback function. One thing to bear in mind is that `requestVideoFrameCallback()` does not offer any strict guarantees that the output from your callback will remain in sync with the video frame rate. It may end up being fired one vertical synchronization (v-sync) later than when the new video frame was presented. (V-sync is a graphics technology that synchronizes the frame rate of a video with the refresh rate of a monitor.) The API runs on the main thread, while video compositing likely happens on a separate compositing thread. You've got to factor in the time taken for these operations to complete, as well as the time it takes for the video itself and the result of your `requestVideoFrameCallback()` operation to display on the screen. You can compare the `now` callback parameter and the `expectedDisplayTime` metadata property to determine whether your callback is a v-sync late. If `expectedDisplayTime` is within about five to ten microseconds of `now`, the frame is already rendered. If the `expectedDisplayTime` is approximately sixteen milliseconds in the future (assuming your browser/screen is refreshing at 60Hz), then the callback is a v-sync out. ## Syntax ```js-nolint requestVideoFrameCallback(callback) ``` ### Parameters - `callback` - : The callback function that runs when a new video frame is sent to the compositor. This contains two parameters: - `now` - : A {{domxref("DOMHighResTimeStamp")}} representing the time when the callback was called. - `metadata` - : An object containing the following properties: - `expectedDisplayTime`: A {{domxref("DOMHighResTimeStamp")}} representing the time when the browser expects the frame to be visible. - `height`: A number, in media pixels, representing the height of the video frame (the visible decoded pixels, without aspect ratio adjustments). - `mediaTime`: A number, in seconds, representing the media presentation timestamp of the presented frame. This is equal to the frame's timestamp on the {{domxref("HTMLMediaElement.currentTime")}} timeline. - `presentationTime`: A {{domxref("DOMHighResTimeStamp")}} representing the time when the browser submitted the frame for composition. - `presentedFrames`: A number representing the number of frames submitted for composition so far alongside the current callback. This can be used to detect whether frames were missed between callback instances. - `processingDuration`: A number, in seconds, representing the duration between the submission of the encoded packet with the same presentation timestamp as this frame to the decoder (i.e., the `mediaTime`) and the decoded frame being ready for presentation. - `width`: A number, in media pixels, representing the width of the video frame (the visible decoded pixels, without aspect ratio adjustments). Additional metadata properties may be available within `requestVideoFrameCallback()` callbacks used in {{domxref("WebRTC_API", "WebRTC", "", "nocode")}} applications: - `captureTime`: A {{domxref("DOMHighResTimeStamp")}} representing the time when the frame was captured. This applies to video frames coming from a local or remote source. For a remote source, the capture time is estimated using clock synchronization and RTCP sender reports to convert RTP timestamps to capture time. - `receiveTime`: A {{domxref("DOMHighResTimeStamp")}} representing the time when the encoded frame was received by the platform. This applies to video frames coming from a remote source. Specifically, this corresponds to the time when the last packet belonging to this frame was received over the network. - `rtpTimestamp`: A number representing the RTP timestamp associated with this video frame. > **Note:** `width` and `height` may differ from {{domxref("HTMLVideoElement.videoWidth")}} and {{domxref("HTMLVideoElement.videoHeight")}} in certain cases (for example, an anamorphic video may have rectangular pixels). ### Return value A number representing a unique callback ID. This can be passed to {{DOMxRef("HTMLVideoElement.cancelVideoFrameCallback()")}} to cancel the callback registration. ## Examples ### Drawing video frames on a canvas This example shows how to use `requestVideoFrameCallback()` to draw the frames of a video onto a {{htmlelement("canvas")}} element at exactly the same frame rate as the video. It also logs the frame metadata to the DOM for debugging purposes. ```js if ("requestVideoFrameCallback" in HTMLVideoElement.prototype) { let paintCount = 0; let startTime = 0.0; const updateCanvas = (now, metadata) => { if (startTime === 0.0) { startTime = now; } ctx.drawImage(video, 0, 0, canvas.width, canvas.height); const elapsed = (now - startTime) / 1000.0; const fps = (++paintCount / elapsed).toFixed(3); fpsInfo.innerText = `video fps: ${fps}`; metadataInfo.innerText = JSON.stringify(metadata, null, 2); // Re-register the callback to run on the next frame video.requestVideoFrameCallback(updateCanvas); }; // Initial registration of the callback to run on the first frame video.requestVideoFrameCallback(updateCanvas); } else { alert("Your browser does not support requestVideoFrameCallback()."); } ``` See [requestVideoFrameCallback Demo](https://requestvideoframecallback.glitch.me/) for a working implementation of the above code. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("video")}} element - {{DOMxRef("HTMLVideoElement.cancelVideoFrameCallback()")}} - [Perform efficient per-video-frame operations on video with `requestVideoFrameCallback()`](https://web.dev/articles/requestvideoframecallback-rvfc) on developer.chrome.com (2023)
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/enterpictureinpicture_event/index.md
--- title: "HTMLVideoElement: enterpictureinpicture event" short-title: enterpictureinpicture slug: Web/API/HTMLVideoElement/enterpictureinpicture_event page-type: web-api-event browser-compat: api.HTMLVideoElement.enterpictureinpicture_event --- {{APIRef("Picture-in-Picture API")}} The `enterpictureinpicture` event is fired when the {{DOMxRef("HTMLVideoElement")}} enters picture-in-picture mode successfully. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("enterpictureinpicture", (event) => {}); onenterpictureinpicture = (event) => {}; ``` ## Event type A {{domxref("PictureInPictureEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PictureInPictureEvent")}} ## Event properties This interface also inherits properties from its parent {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLVideoElement's `enterpictureinpicture` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("#video"); const button = document.querySelector("#button"); function onEnterPip() { console.log("Picture-in-Picture mode activated!"); } video.addEventListener("enterpictureinpicture", onEnterPip, false); button.onclick = () => { video.requestPictureInPicture(); }; ``` Using the `onenterpictureinpicture` event handler property: ```js const video = document.querySelector("#video"); const button = document.querySelector("#button"); function onEnterPip() { console.log("Picture-in-Picture mode activated!"); } video.onenterpictureinpicture = onEnterPip; button.onclick = () => { video.requestPictureInPicture(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLVideoElement")}} - {{domxref("Picture-in-Picture_API", "Picture-in-Picture API")}}
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/getvideoplaybackquality/index.md
--- title: "HTMLVideoElement: getVideoPlaybackQuality() method" short-title: getVideoPlaybackQuality() slug: Web/API/HTMLVideoElement/getVideoPlaybackQuality page-type: web-api-instance-method browser-compat: api.HTMLVideoElement.getVideoPlaybackQuality --- {{ APIRef("HTML DOM") }} The **{{domxref("HTMLVideoElement")}}** method **`getVideoPlaybackQuality()`** creates and returns a {{domxref("VideoPlaybackQuality")}} object containing metrics including how many frames have been lost. The data returned can be used to evaluate the quality of the video stream. ## Syntax ```js-nolint getVideoPlaybackQuality() ``` ### Parameters None. ### Return value A {{domxref("VideoPlaybackQuality")}} object providing information about the video element's current playback quality. ## Examples This example updates an element to indicate the total number of video frames that have elapsed so far in the playback process. This value includes any dropped or corrupted frames, so it's not the same as "total number of frames played." ```js const videoElem = document.getElementById("my_vid"); const counterElem = document.getElementById("counter"); const quality = videoElem.getVideoPlaybackQuality(); counterElem.innerText = quality.totalVideoFrames; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("video")}} element - The {{domxref("VideoPlaybackQuality")}} interface.
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/disablepictureinpicture/index.md
--- title: "HTMLVideoElement: disablePictureInPicture property" short-title: disablePictureInPicture slug: Web/API/HTMLVideoElement/disablePictureInPicture page-type: web-api-instance-property browser-compat: api.HTMLVideoElement.disablePictureInPicture --- {{APIRef("Picture-in-Picture API")}} The {{domxref("HTMLVideoElement")}} **`disablePictureInPicture`** property reflects the HTML attribute indicating whether the picture-in-picture feature is disabled for the current element. ## Value A boolean value that is `true` if the picture-in-picture feature is disabled for this element. This means that the user agent should not suggest that feature to users, or request it automatically. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/leavepictureinpicture_event/index.md
--- title: "HTMLVideoElement: leavepictureinpicture event" short-title: leavepictureinpicture slug: Web/API/HTMLVideoElement/leavepictureinpicture_event page-type: web-api-event browser-compat: api.HTMLVideoElement.leavepictureinpicture_event --- {{APIRef("Picture-in-Picture API")}} The `leavepictureinpicture` event is fired when the {{DOMxRef("HTMLVideoElement")}} leaves picture-in-picture mode successfully. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("leavepictureinpicture", (event) => {}); onleavepictureinpicture = (event) => {}; ``` ## Event type A {{domxref("PictureInPictureEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PictureInPictureEvent")}} ## Event properties This interface also inherits properties from its parent {{domxref("Event")}}. ## Examples These examples add an event listener for the HTMLVideoElement's `leavepictureinpicture` event, then post a message when that event handler has reacted to the event firing. Using `addEventListener()`: ```js const video = document.querySelector("#video"); const button = document.querySelector("#button"); function onExitPip() { console.log("Picture-in-Picture mode deactivated!"); } video.addEventListener("leavepictureinpicture", onExitPip, false); button.onclick = () => { if (document.pictureInPictureElement) { document.exitPictureInPicture(); } }; ``` Using the `onleavepictureinpicture` event handler property: ```js const video = document.querySelector("#video"); const button = document.querySelector("#button"); function onExitPip() { console.log("Picture-in-Picture mode deactivated!"); } video.onleavepictureinpicture = onExitPip; button.onclick = () => { if (document.pictureInPictureElement) { document.exitPictureInPicture(); } }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLVideoElement")}} - {{domxref("Picture-in-Picture_API", "Picture-in-Picture API")}}
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/videoheight/index.md
--- title: "HTMLVideoElement: videoHeight property" short-title: videoHeight slug: Web/API/HTMLVideoElement/videoHeight page-type: web-api-instance-property browser-compat: api.HTMLVideoElement.videoHeight --- {{APIRef("HTML DOM")}} The {{domxref("HTMLVideoElement")}} interface's read-only **`videoHeight`** property indicates the [intrinsic height](#about_intrinsic_width_and_height) of the video, expressed in CSS pixels. In simple terms, this is the height of the media in its natural size. ## Value An integer value specifying the intrinsic height of the video in CSS pixels. If the element's {{domxref("HTMLMediaElement.readyState", "readyState")}} is `HTMLMediaElement.HAVE_NOTHING`, then the value of this property is 0, because neither video nor poster frame size information is yet available. ### About intrinsic width and height A {{Glossary("user agent")}} calculates the intrinsic width and height of the element's media by starting with the media's raw pixel width and height, then taking into account factors including: - The media's aspect ratio. - The media's clean aperture (the sub-rectangle centered within the media that matches the target aspect ratio). - The target device's resolution. - Any other factors required by the media format. If the element is currently displaying the poster frame rather than rendered video, the poster frame's intrinsic size is considered to be the size of the `<video>` element. If at any time the intrinsic size of the media changes and the element's {{domxref("HTMLMediaElement.readyState", "readyState")}} isn't `HAVE_NOTHING`, a {{domxref("HTMLMediaElement.resize", "resize")}} event will be sent to the `<video>` element. This can happen when the element switches from displaying the poster frame to displaying video content, or when the displayed video track changes. ## Examples This example creates a handler for the {{domxref("HTMLVideoElement.resize", "resize")}} event that resizes the {{HTMLElement("video")}} element to match the intrinsic size of its contents. ```js let v = document.getElementById("myVideo"); v.addEventListener( "resize", (ev) => { let w = v.videoWidth; let h = v.videoHeight; if (w && h) { v.style.width = w; v.style.height = h; } }, false, ); ``` Note that this only applies the change if both the `videoWidth` and the `videoHeight` are non-zero. This avoids applying invalid changes when there's no true information available yet for dimensions. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/requestpictureinpicture/index.md
--- title: "HTMLVideoElement: requestPictureInPicture() method" short-title: requestPictureInPicture() slug: Web/API/HTMLVideoElement/requestPictureInPicture page-type: web-api-instance-method browser-compat: api.HTMLVideoElement.requestPictureInPicture --- {{APIRef("Picture-in-Picture API")}} The **{{domxref("HTMLVideoElement")}}** method **`requestPictureInPicture()`** issues an asynchronous request to display the video in picture-in-picture mode. It's not guaranteed that the video will be put into picture-in-picture. If permission to enter that mode is granted, the returned {{jsxref("Promise")}} will resolve and the video will receive a {{domxref("HTMLVideoElement.enterpictureinpicture_event", "enterpictureinpicture")}} event to let it know that it's now in picture-in-picture. ## Syntax ```js-nolint requestPictureInPicture() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that will resolve to a {{domxref("PictureInPictureWindow")}} object that can be used to listen when a user will resize that floating window. ### Exceptions - `NotSupportedError` {{domxref("DOMException")}} - : Thrown if the feature is not supported (for example, disabled by a user preference or by a platform limitation). - `SecurityError` {{domxref("DOMException")}} - : Thrown if the feature is blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the video element's `readState` is `HAVE_NOTHING`, or if the video element has no video track, or if the video element's `disablePictureInPicture` attribute is `true`. - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if `document.pictureInPictureElement` is `null` and the document does not have {{Glossary("transient activation")}}. ## 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 for this feature to work. ## Examples This example requests that the video enters Picture-in-Picture mode, and sets an event listener to handle the floating window resizing. ```js function enterPictureInPicture() { videoElement.requestPictureInPicture().then((pictureInPictureWindow) => { pictureInPictureWindow.addEventListener( "resize", () => onPipWindowResize(), false, ); }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("video")}} element - {{DOMxRef("HTMLVideoElement.disablePictureInPicture")}} - {{DOMxRef("Document.pictureInPictureEnabled")}} - {{DOMxRef("Document.exitPictureInPicture()")}} - {{DOMxRef("Document.pictureInPictureElement")}} - {{CSSxRef(":picture-in-picture")}}
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/width/index.md
--- title: "HTMLVideoElement: width property" short-title: width slug: Web/API/HTMLVideoElement/width page-type: web-api-instance-property browser-compat: api.HTMLVideoElement.width --- {{APIRef("HTML DOM")}} The **`width`** property of the {{domxref("HTMLVideoElement")}} interface returns an integer that that reflects the `width` attribute of the {{HTMLElement("video")}} element, specifying the displayed width of the resource in CSS pixels. ## Value A positive integer or 0. ## Examples ```html <video id="media" width="800" height="600"></video> ``` ```js const el = document.getElementById("media"); console.log(el.width); // Output: 800 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement.width")}} - {{domxref("HTMLEmbedElement.width")}} - {{domxref("HTMLIFrameElement.width")}} - {{domxref("HTMLImageElement.width")}} - {{domxref("HTMLObjectElement.width")}} - {{domxref("HTMLSourceElement.width")}}
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/height/index.md
--- title: "HTMLVideoElement: height property" short-title: height slug: Web/API/HTMLVideoElement/height page-type: web-api-instance-property browser-compat: api.HTMLVideoElement.height --- {{APIRef("HTML DOM")}} The **`height`** property of the {{domxref("HTMLVideoElement")}} interface returns an integer that reflects the `height` attribute of the {{HTMLElement("video")}} element, specifying the displayed height of the resource in CSS pixels. ## Value A positive integer or 0. ## Examples ```html <video id="media" width="800" height="600"></video> ``` ```js const el = document.getElementById("media"); console.log(el.height); // Output: 600 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("HTMLCanvasElement.height")}} - {{domxref("HTMLEmbedElement.height")}} - {{domxref("HTMLIFrameElement.height")}} - {{domxref("HTMLImageElement.height")}} - {{domxref("HTMLObjectElement.height")}} - {{domxref("HTMLSourceElement.height")}}
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/cancelvideoframecallback/index.md
--- title: "HTMLVideoElement: cancelVideoFrameCallback() method" short-title: cancelVideoFrameCallback() slug: Web/API/HTMLVideoElement/cancelVideoFrameCallback page-type: web-api-instance-method browser-compat: api.HTMLVideoElement.cancelVideoFrameCallback --- {{APIRef("HTML DOM")}} The **`cancelVideoFrameCallback()`** method of the {{domxref("HTMLVideoElement")}} interface cancels a previously-registered video frame callback. ## Syntax ```js-nolint cancelVideoFrameCallback(id) ``` ### Parameters - `id` - : A number representing the ID of the video frame callback you want to cancel. This will be the value returned by the corresponding {{DOMxRef("HTMLVideoElement.requestVideoFrameCallback")}} call. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Canceling a video frame callback This example shows how to use `cancelVideoFrameCallback()` to cancel a previously-registered video frame callback. ```js const updateCanvas = (now, metadata) => { // Do something with the frame // ... // Re-register the callback to run on the next frame // It's important to update the videoCallbackId on each iteration // so you can cancel the callback successfully videoCallbackId = video.requestVideoFrameCallback(updateCanvas); }; // Initial registration of the callback to run on the first frame let videoCallbackId = video.requestVideoFrameCallback(updateCanvas); // ... // Cancel video frame callback using the latest videoCallbackId video.cancelVideoFrameCallback(videoCallbackId); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{HTMLElement("video")}} element - {{DOMxRef("HTMLVideoElement.requestVideoFrameCallback()")}} - [Perform efficient per-video-frame operations on video with `requestVideoFrameCallback()`](https://web.dev/articles/requestvideoframecallback-rvfc) on developer.chrome.com (2023)
0
data/mdn-content/files/en-us/web/api/htmlvideoelement
data/mdn-content/files/en-us/web/api/htmlvideoelement/poster/index.md
--- title: "HTMLVideoElement: poster property" short-title: poster slug: Web/API/HTMLVideoElement/poster page-type: web-api-instance-property browser-compat: api.HTMLVideoElement.poster --- {{APIRef("HTML DOM")}} The **`poster`** property of the {{domxref("HTMLVideoElement")}} interface is a string that reflects the URL for an image to be shown while no video data is available. If the property does not represent a valid URL, no poster frame will be shown. It reflects the `poster` attribute of the {{HTMLElement("video")}} element. ## Value A string. ## Examples ```html <video id="media" src="https://example.com/video.mp4" poster="https://example.com/poster.jpg"></video> ``` ```js const el = document.getElementById("media"); console.log(el.poster); // Output: "https://example.com/poster.jpg" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/pointer_events/index.md
--- title: Pointer events slug: Web/API/Pointer_events page-type: web-api-overview browser-compat: api.PointerEvent spec-urls: https://w3c.github.io/pointerevents/ --- {{DefaultAPISidebar("Pointer Events")}} Much of today's web content assumes the user's pointing device will be a mouse. However, since many devices support other types of pointing input devices, such as pen/stylus and touch surfaces, extensions to the existing pointing device event models are needed. _[Pointer events](#pointer_event)_ address that need. Pointer events are DOM events that are fired for a pointing device. They are designed to create a single DOM event model to handle pointing input devices such as a mouse, pen/stylus or touch (such as one or more fingers). The _[pointer](#pointer)_ is a hardware-agnostic device that can target a specific set of screen coordinates. Having a single event model for pointers can simplify creating websites and applications and provide a good user experience regardless of the user's hardware. However, for scenarios when device-specific handling is desired, pointer events defines a {{domxref("PointerEvent.pointerType","pointerType property")}} to inspect the device type which produced the event. The events needed to handle generic pointer input are analogous to {{domxref("MouseEvent","mouse events")}} (`mousedown`/`pointerdown`, `mousemove`/`pointermove`, etc.). Consequently, pointer event types are intentionally similar to mouse event types. Additionally, a pointer event contains the usual properties present in mouse events (client coordinates, target element, button states, etc.) in addition to new properties for other forms of input: pressure, contact geometry, tilt, etc. In fact, the {{domxref("PointerEvent")}} interface inherits all of the {{domxref("MouseEvent")}} properties, thus facilitating the migration of content from mouse events to pointer events. ## Terminology ### active buttons state The condition when a _[pointer](#pointer)_ has a non-zero value for the `buttons` property. For example, in the case of a pen, when the pen has physical contact with the digitizer, or at least one button is pressed while hovering. ### active pointer Any _[pointer](#pointer)_ input device that can produce events. A pointer is considered active if it can still produce further events. For example, a pen that is a down state is considered active because it can produce additional events when the pen is lifted or moved. ### digitizer A sensing device with a surface that can detect contact. Most commonly, the sensing device is a touch-enabled screen that can sense input from an input device such as a pen, stylus, or finger. Some sensing devices can detect the close proximity of the input device, and the state is expressed as a hover following the mouse. ### hit test The process the browser uses to determine a target element for a pointer event. Typically, this is determined by considering the pointer's location and also the visual layout of elements in a document on screen media. ### pointer A hardware-agnostic representation of input devices that can target a specific coordinate (or set of coordinates) on a screen. Examples of _pointer_ input devices are mouse, pen/stylus, and touch contacts. ### pointer capture Pointer capture allows the events for a pointer to be retargeted to a particular element other than the normal hit test result of the pointer's location. ### pointer event A DOM {{domxref("PointerEvent","event")}} fired for a _[pointer](#pointer)_. ## Interfaces The primary interface is the {{domxref("PointerEvent")}} interface which has a {{domxref("PointerEvent.PointerEvent","constructor")}} plus several event types and associated global event handlers. The standard also includes some extensions to the {{domxref("Element")}} and {{domxref("Navigator")}} interfaces. The following sub-sections contain short descriptions of each interface and property. ### PointerEvent interface The {{domxref("PointerEvent")}} interface extends the {{domxref("MouseEvent")}} interface and has the following properties. - {{ domxref('PointerEvent.altitudeAngle', 'altitudeAngle')}} {{ReadOnlyInline}} {{experimental_inline}} - : Represents the angle between a transducer (a pointer or stylus) axis and the X-Y plane of a device screen. - {{ domxref('PointerEvent.azimuthAngle', 'azimuthAngle')}} {{ReadOnlyInline}} {{experimental_inline}} - : Represents the angle between the Y-Z plane and the plane containing both the transducer (a pointer or stylus) axis and the Y axis. - {{ domxref('PointerEvent.pointerId','pointerId')}} {{ReadOnlyInline}} - : A unique identifier for the pointer causing the event. - {{ domxref('PointerEvent.width','width')}} {{ReadOnlyInline}} - : The width (magnitude on the X axis), in CSS pixels, of the contact geometry of the pointer. - {{ domxref('PointerEvent.height','height')}} {{ReadOnlyInline}} - : the height (magnitude on the Y axis), in CSS pixels, of the contact geometry of the pointer. - {{ domxref('PointerEvent.pressure','pressure')}} {{ReadOnlyInline}} - : the normalized pressure of the pointer input in the range of `0` to `1`, where `0` and `1` represent the minimum and maximum pressure the hardware is capable of detecting, respectively. - {{ domxref('PointerEvent.tangentialPressure','tangentialPressure')}} {{ReadOnlyInline}} - : The normalized tangential pressure of the pointer input (also known as barrel pressure or cylinder stress) in the range `-1` to `1`, where `0` is the neutral position of the control. - {{ domxref('PointerEvent.tiltX','tiltX')}} {{ReadOnlyInline}} - : The plane angle (in degrees, in the range of `-90` to `90`) between the Y–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the Y axis. - {{ domxref('PointerEvent.tiltY','tiltY')}} {{ReadOnlyInline}} - : the plane angle (in degrees, in the range of `-90` to `90`) between the X–Z plane and the plane containing both the pointer (e.g. pen stylus) axis and the X axis. - {{ domxref('PointerEvent.twist','twist')}} {{ReadOnlyInline}} - : The clockwise rotation of the pointer (e.g. pen stylus) around its major axis in degrees, with a value in the range `0` to `359`. - {{ domxref('PointerEvent.pointerType','pointerType')}} {{ReadOnlyInline}} - : Indicates the device type that caused the event (mouse, pen, touch, etc.). - {{ domxref('PointerEvent.isPrimary','isPrimary')}} {{ReadOnlyInline}} - : Indicates if the pointer represents the primary pointer of this pointer type. ### Event types and Global Event Handlers Pointer events have ten event types, seven of which have similar semantics to their mouse event counterparts (`down`, `up`, `move`, `over`, `out`, `enter`, and `leave`). Below is a short description of each event type. | Event | Description | | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | {{domxref('Element/pointerover_event', 'pointerover')}} | Fired when a pointer is moved into an element's [hit test](#hit_test) boundaries. | | {{domxref('Element/pointerenter_event', 'pointerenter')}} | Fired when a pointer is moved into the [hit test](#hit_test) boundaries of an element or one of its descendants, including as a result of a `pointerdown` event from a device that does not support hover (see `pointerdown`). | | {{domxref('Element/pointerdown_event', 'pointerdown')}} | Fired when a pointer becomes _active buttons state_. | | {{domxref('Element/pointermove_event', 'pointermove')}} | Fired when a pointer changes coordinates. This event is also used if the change in pointer state cannot be reported by other events. | | {{domxref('Element/pointerup_event', 'pointerup')}} | Fired when a pointer is no longer _active buttons state_. | | {{domxref('Element/pointercancel_event', 'pointercancel')}} | A browser fires this event if it concludes the pointer will no longer be able to generate events (for example the related device is deactivated). | | {{domxref('Element/pointerout_event', 'pointerout')}} | Fired for several reasons including: pointer is moved out of the [hit test](#hit_test) boundaries of an element; firing the pointerup event for a device that does not support hover (see `pointerup`); after firing the `pointercancel` event (see `pointercancel`); when a pen stylus leaves the hover range detectable by the digitizer. | | {{domxref('Element/pointerleave_event', 'pointerleave')}} | Fired when a pointer is moved out of the [hit test](#hit_test) boundaries of an element. For pen devices, this event is fired when the stylus leaves the hover range detectable by the digitizer. | | {{domxref('Element/pointerrawupdate_event', 'pointerrawupdate')}} {{experimental_inline}} | Fired when a pointer changes any properties that don't fire `pointerdown` or `pointerup` events. | | {{domxref('Element/gotpointercapture_event', 'gotpointercapture')}} | Fired when an element receives pointer capture. | | {{domxref('Element/lostpointercapture_event', 'lostpointercapture')}} | Fired after pointer capture is released for a pointer. | ### Element extensions There are three extensions to the {{domxref("Element")}} interface: - {{domxref("Element.hasPointerCapture()","hasPointerCapture()")}} - : Indicates whether the element on which it is invoked has pointer capture for the pointer identified by the given pointer ID. - {{domxref("Element.releasePointerCapture()","releasePointerCapture()")}} - : Releases (stops) _pointer capture_ that was previously set for a specific pointer event. - {{domxref("Element.setPointerCapture()","setPointerCapture()")}} - : Designates a specific element as the _capture target_ of future pointer events. ### Navigator extension The {{domxref("Navigator.maxTouchPoints")}} property is used to determine the maximum number of simultaneous touch points that are supported at any single point in time. ## Examples This section contains examples of basic usage of using the pointer events interfaces. ### Registering event handlers This example registers a handler for every event type for the given element. ```html <html lang="en"> <script> function over_handler(event) {} function enter_handler(event) {} function down_handler(event) {} function move_handler(event) {} function up_handler(event) {} function cancel_handler(event) {} function out_handler(event) {} function leave_handler(event) {} function rawupdate_handler(event) {} function gotcapture_handler(event) {} function lostcapture_handler(event) {} function init() { const el = document.getElementById("target"); // Register pointer event handlers el.onpointerover = over_handler; el.onpointerenter = enter_handler; el.onpointerdown = down_handler; el.onpointermove = move_handler; el.onpointerup = up_handler; el.onpointercancel = cancel_handler; el.onpointerout = out_handler; el.onpointerleave = leave_handler; el.onpointerrawupdate = rawupdate_handler; el.ongotpointercapture = gotcapture_handler; el.onlostpointercapture = lostcapture_handler; } </script> <body onload="init();"> <div id="target">Touch me…</div> </body> </html> ``` ### Event properties This example illustrates accessing all of a pointer event's properties. ```html <html lang="en"> <script> const id = -1; function process_id(event) { // Process this event based on the event's identifier } function process_mouse(event) { // Process the mouse pointer event } function process_pen(event) { // Process the pen pointer event } function process_touch(event) { // Process the touch pointer event } function process_tilt(tiltX, tiltY) { // Tilt data handler } function process_pressure(pressure) { // Pressure handler } function process_non_primary(event) { // Non primary handler } function down_handler(ev) { // Calculate the touch point's contact area const area = ev.width * ev.height; // Compare cached id with this event's id and process accordingly if (id === ev.identifier) process_id(ev); // Call the appropriate pointer type handler switch (ev.pointerType) { case "mouse": process_mouse(ev); break; case "pen": process_pen(ev); break; case "touch": process_touch(ev); break; default: console.log(`pointerType ${ev.pointerType} is not supported`); } // Call the tilt handler if (ev.tiltX !== 0 && ev.tiltY !== 0) process_tilt(ev.tiltX, ev.tiltY); // Call the pressure handler process_pressure(ev.pressure); // If this event is not primary, call the non primary handler if (!ev.isPrimary) process_non_primary(ev); } function init() { const el = document.getElementById("target"); // Register pointerdown handler el.onpointerdown = down_handler; } </script> <body onload="init();"> <div id="target">Touch me…</div> </body> </html> ``` ## Determining the Primary Pointer In some scenarios there may be multiple pointers (for example a device with both a touchscreen and a mouse), or a pointer that supports multiple contact points (for example a touchscreen that supports multiple finger touches). The application can use the {{domxref("PointerEvent.isPrimary","isPrimary")}} property to identify a master pointer among the set of _active pointers_ for each pointer type. If an application only wants to support a primary pointer, it can ignore all pointer events that are not primary. A mouse has only one pointer, so it will always be the primary pointer. For touch input, a pointer is considered primary if the user touched the screen when there were no other active touches. For pen and stylus input, a pointer is considered primary if the user's pen initially contacted the screen when there were no other active pens contacting the screen. ## Determining button states Some pointer devices (such as mouse and pen) support multiple buttons, and the button presses can be _chorded_ (i.e. pressing an additional button while another button on the pointer device is already pressed). To determine the state of button presses, pointer events uses the {{domxref("MouseEvent.button","button")}} and {{domxref("MouseEvent.buttons","buttons")}} properties of the {{domxref("MouseEvent")}} interface (that {{domxref("PointerEvent")}} inherits from). The following table provides the values of `button` and `buttons` for the various device button states. | Device Button State | button | buttons | | ------------------------------------------------------------------------------------ | ------ | ------- | | Neither buttons nor touch/pen contact changed since last event | `-1` | β€” | | Mouse move with no buttons pressed, Pen moved while hovering with no buttons pressed | β€” | `0` | | Left Mouse, Touch Contact, Pen contact | `0` | `1` | | Middle Mouse | `1` | `4` | | Right Mouse, Pen barrel button | `2` | `2` | | X1 (back) Mouse | `3` | `8` | | X2 (forward) Mouse | `4` | `16` | | Pen eraser button | `5` | `32` | > **Note:** The `button` property indicates a change in the state of the button. However, as in the case of touch, when multiple events occur with one event, all of them have the same value. ## Capturing the pointer Pointer capture allows events for a particular {{domxref("PointerEvent","pointer event")}} to be re-targeted to a particular element instead of the normal [hit test](#hit_test) at a pointer's location. This can be used to ensure that an element continues to receive pointer events even if the pointer device's contact moves off the element (for example by scrolling). The following example shows pointer capture being set on an element. ```html <html lang="en"> <script> function downHandler(ev) { let el = document.getElementById("target"); // Element 'target' will receive/capture further events el.setPointerCapture(ev.pointerId); } function init() { let el = document.getElementById("target"); el.onpointerdown = downHandler; } </script> <body onload="init();"> <div id="target">Touch me…</div> </body> </html> ``` The following example shows a pointer capture being released (when a {{domxref("Element/pointercancel_event", "pointercancel")}} event occurs. The browser does this automatically when a {{domxref("Element/pointerup_event", "pointerup")}} or {{domxref("Element/pointercancel_event", "pointercancel")}} event occurs. ```html <html lang="en"> <script> function downHandler(ev) { let el = document.getElementById("target"); // Element "target" will receive/capture further events el.setPointerCapture(ev.pointerId); } function cancelHandler(ev) { let el = document.getElementById("target"); // Release the pointer capture el.releasePointerCapture(ev.pointerId); } function init() { let el = document.getElementById("target"); // Register pointerdown and pointercancel handlers el.onpointerdown = downHandler; el.onpointercancel = cancelHandler; } </script> <body onload="init();"> <div id="target">Touch me…</div> </body> </html> ``` ## touch-action CSS property The {{cssxref("touch-action")}} CSS property is used to specify whether or not the browser should apply its default (_native_) touch behavior (such as zooming or panning) to a region. This property may be applied to all elements except: non-replaced inline elements, table rows, row groups, table columns, and column groups. A value of `auto` means the browser is free to apply its default touch behavior (to the specified region) and the value of `none` disables the browser's default touch behavior for the region. The values `pan-x` and `pan-y`, mean that touches that begin on the specified region are only for horizontal and vertical scrolling, respectively. The value `manipulation` means the browser may consider touches that begin on the element are only for scrolling and zooming. In the following example, the browser's default touch behavior is disabled for the `div` element. ```html <html lang="en"> <body> <div style="touch-action:none;">Can't touch this…</div> </body> </html> ``` In the following example, default touch behavior is disabled for some `button` elements. ```css button#tiny { touch-action: none; } ``` In the following example, when the `target` element is touched, it will only pan in the horizontal direction. ```css #target { touch-action: pan-x; } ``` ## Compatibility with mouse events Although the pointer event interfaces enable applications to create enhanced user experiences on pointer enabled devices, the reality is the vast majority of today's web content is designed to only work with mouse input. Consequently, even if a browser supports pointer events, the browser must still process mouse events so content that assumes mouse-only input will work as is without direct modification. Ideally, a pointer enabled application does not need to explicitly handle mouse input. However, because the browser must process mouse events, there may be some compatibility issues that need to be handled. This section contains information about pointer event and mouse event interaction and the ramifications for application developers. The browser _may map generic pointer input to mouse events for compatibility with mouse-based content_. This mapping of events is called _compatibility mouse events_. Authors can prevent the production of certain compatibility mouse events by canceling the pointerdown event but note that: - Mouse events can only be prevented when the pointer is down. - Hovering pointers (e.g. a mouse with no buttons pressed) cannot have their mouse events prevented. - The `mouseover`, `mouseout`, `mouseenter`, and `mouseleave` events are never prevented (even if the pointer is down). ## Best practices Here are some _best practices_ to consider when using pointer events: - Minimize the amount of work performed in event handlers. - Add the event handlers to a specific target element (rather than the entire document or nodes higher up in the document tree). - The target element (node) should be large enough to accommodate the largest contact surface area (typically a finger touch). If the target area is too small, touching it could result in firing other events for adjacent elements. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} Some additional values have been defined for the {{cssxref("touch-action", "CSS touch-action")}} property as part of the [Pointer Events](https://w3c.github.io/pointerevents/) specification, but currently those values have limited implementation support. ## See also ### Demos and examples - [Touch/pointer tests and demos (by Patrick H. Lauke)](https://patrickhlauke.github.io/touch/) ### Community - [Pointer Events Working Group](https://github.com/w3c/pointerevents) - [Mail list](https://lists.w3.org/Archives/Public/public-pointer-events/) - [W3C #pointerevents IRC channel](irc://irc.w3.org:6667/) ### Related topics and resources - [Touch Events Standard](https://www.w3.org/TR/touch-events/)
0
data/mdn-content/files/en-us/web/api/pointer_events
data/mdn-content/files/en-us/web/api/pointer_events/pinch_zoom_gestures/index.md
--- title: Pinch zoom gestures slug: Web/API/Pointer_events/Pinch_zoom_gestures page-type: guide --- {{DefaultAPISidebar("Pointer Events")}} Adding _gestures_ to an application can significantly improve the user experience. There are many types of gestures, from the simple single-touch _swipe_ gesture to the more complex multi-touch _twist_ gesture, where the touch points (aka _pointers_) move in different directions. This example shows how to detect the _pinch/zoom_ gesture, which uses {{domxref("Pointer_events","pointer events")}} to detect whether the user moves two pointers closer or farther apart from each other. A _live_ version of this application is available on [GitHub](https://mdn.github.io/dom-examples/pointerevents/Pinch_zoom_gestures.html). The [source code is available on GitHub](https://github.com/mdn/dom-examples/blob/main/pointerevents/Pinch_zoom_gestures.html); pull requests and [bug reports](https://github.com/mdn/dom-examples/issues) are welcome. ## Example In this example, you use the {{domxref("Pointer_events","pointer events")}} to simultaneously detect two pointing devices of any type, including fingers, mice, and pens. The pinch in (zoom out) gesture, which moves the two pointers toward each other, changes the target element's background color to `lightblue`. The pinch out (zoom in) gesture, which moves the two pointers away from each other, changes the target element's background color to `pink`. ### Define touch target The application uses {{HTMLElement("div")}} to define the pointers' target areas. ```html <style> div { margin: 0em; padding: 2em; } #target { background: white; border: 1px solid black; } </style> ``` ### Global state Supporting a two-pointer gesture requires preserving a pointer's event state during various event phases. This application uses two global variables to cache the event state. ```js // Global vars to cache event state const evCache = []; let prevDiff = -1; ``` ### Register event handlers Event handlers are registered for the following pointer events: {{domxref("Element/pointerdown_event", "pointerdown")}}, {{domxref("Element/pointermove_event", "pointermove")}} and {{domxref("Element/pointerup_event", "pointerup")}}. The handler for {{domxref("Element/pointerup_event", "pointerup")}} is used for the {{domxref("Element/pointercancel_event", "pointercancel")}}, {{domxref("Element/pointerout_event", "pointerout")}} and {{domxref("Element/pointerleave_event", "pointerleave")}} events since these four events have the same semantics in this application. ```js function init() { // Install event handlers for the pointer target const el = document.getElementById("target"); el.onpointerdown = pointerdownHandler; el.onpointermove = pointermoveHandler; // Use same handler for pointer{up,cancel,out,leave} events since // the semantics for these events - in this app - are the same. el.onpointerup = pointerupHandler; el.onpointercancel = pointerupHandler; el.onpointerout = pointerupHandler; el.onpointerleave = pointerupHandler; } ``` ### Pointer down The {{domxref("Element/pointerdown_event", "pointerdown")}} event is fired when a pointer (mouse, pen/stylus or touch point on a touchscreen) makes contact with the _contact surface_. In this application, the event's state must be cached in case this down event is part of a two-pointer pinch/zoom gesture. ```js function pointerdownHandler(ev) { // The pointerdown event signals the start of a touch interaction. // This event is cached to support 2-finger gestures evCache.push(ev); log("pointerDown", ev); } ``` ### Pointer move The {{domxref("Element/pointermove_event", "pointermove")}} event handler detects if a user is invoking a two-pointer pinch/zoom gesture. If two pointers are down, and the distance between the pointers is increasing (signifying a pinch out or zoom in), the element's background color is changed to `pink`, and if the distance between the pointers is decreasing (a pinch in or zoom out), the background color is changed to `lightblue`. In a more sophisticated application, pinch in or pinch out determination could be used to apply application-specific semantics. When this event is processed, the target's border is set to `dashed` to provide a clear visual indication the element has received a move event. ```js function pointermoveHandler(ev) { // This function implements a 2-pointer horizontal pinch/zoom gesture. // // If the distance between the two pointers has increased (zoom in), // the target element's background is changed to "pink" and if the // distance is decreasing (zoom out), the color is changed to "lightblue". // // This function sets the target element's border to "dashed" to visually // indicate the pointer's target received a move event. log("pointerMove", ev); ev.target.style.border = "dashed"; // Find this event in the cache and update its record with this event const index = evCache.findIndex( (cachedEv) => cachedEv.pointerId === ev.pointerId, ); evCache[index] = ev; // If two pointers are down, check for pinch gestures if (evCache.length === 2) { // Calculate the distance between the two pointers const curDiff = Math.abs(evCache[0].clientX - evCache[1].clientX); if (prevDiff > 0) { if (curDiff > prevDiff) { // The distance between the two pointers has increased log("Pinch moving OUT -> Zoom in", ev); ev.target.style.background = "pink"; } if (curDiff < prevDiff) { // The distance between the two pointers has decreased log("Pinch moving IN -> Zoom out", ev); ev.target.style.background = "lightblue"; } } // Cache the distance for the next move event prevDiff = curDiff; } } ``` ### Pointer up The {{domxref("Element/pointerup_event", "pointerup")}} event is fired when a pointer is raised from the _contact surface_. When this occurs, the event is removed from the event cache and the target element's background color and border are restored to their original values. In this application, this handler is also used for {{domxref("Element/pointercancel_event", "pointercancel")}}, {{domxref("Element/pointerleave_event", "pointerleave")}} and {{domxref("Element/pointerout_event", "pointerout")}} events. ```js function pointerupHandler(ev) { log(ev.type, ev); // Remove this pointer from the cache and reset the target's // background and border removeEvent(ev); ev.target.style.background = "white"; ev.target.style.border = "1px solid black"; // If the number of pointers down is less than two then reset diff tracker if (evCache.length < 2) { prevDiff = -1; } } ``` ### Application UI The application uses a {{HTMLElement("div")}} element for the touch area and provides buttons to enable logging and to clear the log. To prevent the browser's default touch behavior from overriding this application's pointer handling, the {{cssxref("touch-action")}} property is applied to the {{HTMLElement("body")}} element. ```html <body onload="init();" style="touch-action:none"> <div id="target"> Touch and Hold with 2 pointers, then pinch in or out.<br /> The background color will change to pink if the pinch is opening (Zoom In) or changes to lightblue if the pinch is closing (Zoom out). </div> <!-- UI for logging/debugging --> <button id="log" onclick="enableLog(event);">Start/Stop event logging</button> <button id="clearlog" onclick="clearLog(event);">Clear the log</button> <p></p> <output></output> </body> ``` ### Miscellaneous functions These functions support the application but aren't directly involved in the event flow. #### Cache management This function helps manage the global event caches `evCache`. ```js function removeEvent(ev) { // Remove this event from the target's cache const index = evCache.findIndex( (cachedEv) => cachedEv.pointerId === ev.pointerId, ); evCache.splice(index, 1); } ``` #### Event logging These functions are used to send event activity to the application's window (to support debugging and learning about the event flow). ```js // Log events flag let logEvents = false; // Logging/debugging functions function enableLog(ev) { logEvents = !logEvents; } function log(prefix, ev) { if (!logEvents) return; const o = document.getElementsByTagName("output")[0]; const s = `${prefix}:<br>` + ` pointerID = ${ev.pointerId}<br>` + ` pointerType = ${ev.pointerType}<br>` + ` isPrimary = ${ev.isPrimary}`; o.innerHTML += `${s}<br>`; } function clearLog(event) { const o = document.getElementsByTagName("output")[0]; o.innerHTML = ""; } ``` ## See also - [Pointer Events now in Firefox Nightly](https://hacks.mozilla.org/2015/08/pointer-events-now-in-firefox-nightly/); Mozilla Hacks; by Matt Brubeck and Jason Weathersby; 2015-Aug-04 - [jQuery Pointer Events Polyfill](https://github.com/jquery-archive/PEP) - [Gestures](https://material.io/design/interaction/gestures.html); Material Design
0
data/mdn-content/files/en-us/web/api/pointer_events
data/mdn-content/files/en-us/web/api/pointer_events/using_pointer_events/index.md
--- title: Using Pointer Events slug: Web/API/Pointer_events/Using_Pointer_Events page-type: guide browser-compat: api.PointerEvent --- {{DefaultAPISidebar("Pointer Events")}} This guide demonstrates how to use [pointer events](/en-US/docs/Web/API/Pointer_events) and the HTML {{HTMLElement("canvas")}} element to build a multi-touch enabled drawing application. This example is based on the one in the [touch events overview](/en-US/docs/Web/API/Touch_events), except it uses the {{domxref("PointerEvent","pointer events", "", 1)}} input event model. Another difference is that because pointer events are pointer device agnostic, the application accepts coordinate-based inputs from a mouse, a pen, or a fingertip using the same code. This application will only work on a browser that supports pointer events. A live version of this application is available on [GitHub](https://mdn.github.io/dom-examples/pointerevents/Using_Pointer_Events.html). The [source code is available on GitHub](https://github.com/mdn/dom-examples/blob/main/pointerevents/Using_Pointer_Events.html) and pull requests and bug reports are welcome. ## Definitions - Surface - : A touch-sensitive surface. This may be a trackpad, a touch screen, or even a virtual mapping of a user's desk surface (or mousepad) with the physical screen. - Touch point - : A point of contact with the surface. This may be a finger (or elbow, ear, nose, whatever, but typically a finger), stylus, mouse, or any other method for specifying a single point on the surface. ## Example > **Note:** The text below uses the term "finger" when describing the contact with the surface, but it could, of course, also be a stylus, mouse, or other method of pointing at a location. ### Create a canvas The {{cssxref("touch-action")}} property is set to `none` to prevent the browser from applying its default touch behavior to the application. ```html <canvas id="canvas" width="600" height="600" style="border:solid black 1px; touch-action:none"> Your browser does not support canvas element. </canvas> <br /> <button onclick="startup()">Initialize</button> <br /> Log: <pre id="log" style="border: 1px solid #ccc;"></pre> ``` ### Setting up the event handlers When the page loads, the `startup()` function shown below should be called by our {{HTMLElement("body")}} element's `onload` attribute (but in the example we use a button to trigger it, due to limitations of the MDN live example system). ```js function startup() { const el = document.getElementsByTagName("canvas")[0]; el.addEventListener("pointerdown", handleStart, false); el.addEventListener("pointerup", handleEnd, false); el.addEventListener("pointercancel", handleCancel, false); el.addEventListener("pointermove", handleMove, false); log("initialized."); } ``` This sets up all the event listeners for our {{HTMLElement("canvas")}} element so we can handle the touch events as they occur. #### Tracking new touches We'll keep track of the touches in-progress. ```js const ongoingTouches = []; ``` When a {{domxref("Element/pointerdown_event", "pointerdown")}} event occurs, indicating that a new touch on the surface has occurred, the `handleStart()` function below is called. ```js function handleStart(evt) { log("pointerdown."); const el = document.getElementsByTagName("canvas")[0]; const ctx = el.getContext("2d"); log(`pointerdown: id = ${evt.pointerId}`); ongoingTouches.push(copyTouch(evt)); const color = colorForTouch(evt); ctx.beginPath(); ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false); // a circle at the start ctx.arc(evt.clientX, evt.clientY, 4, 0, 2 * Math.PI, false); // a circle at the start ctx.fillStyle = color; ctx.fill(); } ``` After storing some of the event's processing in the `ongoingTouches` for later processing, the start point is drawn as a small circle. We're using a 4-pixel wide line, so a 4 pixel radius circle will show up neatly. #### Drawing as the pointers move Each time one or more pointers moves, a {{domxref("Element/pointermove_event", "pointermove")}} event is delivered, resulting in our `handleMove()` function being called. Its responsibility in this example is to update the cached touch information and to draw a line from the previous position to the current position of each touch. ```js function handleMove(evt) { const el = document.getElementsByTagName("canvas")[0]; const ctx = el.getContext("2d"); const color = colorForTouch(evt); const idx = ongoingTouchIndexById(evt.pointerId); log(`continuing touch: idx = ${idx}`); if (idx >= 0) { ctx.beginPath(); log( `ctx.moveTo(${ongoingTouches[idx].pageX}, ${ongoingTouches[idx].pageY});`, ); ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY); log(`ctx.lineTo(${evt.clientX}, ${evt.clientY});`); ctx.lineTo(evt.clientX, evt.clientY); ctx.lineWidth = 4; ctx.strokeStyle = color; ctx.stroke(); ongoingTouches.splice(idx, 1, copyTouch(evt)); // swap in the new touch record log("."); } else { log(`can't figure out which touch to continue: idx = ${idx}`); } } ``` This function looks in our cached touch information array for the previous information about each touch to determine the starting point for each touch's new line segment to be drawn. This is done by looking at each touch's {{domxref("PointerEvent.pointerId")}} property. This property is a unique integer for each pointer event, and remains consistent for each event during the duration of each finger's contact with the surface. This lets us get the coordinates of the previous position of each touch and use the appropriate context methods to draw a line segment joining the two positions together. After drawing the line, we call [`Array.splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) to replace the previous information about the touch point with the current information in the `ongoingTouches` array. #### Handling the end of a touch When the user lifts a finger off the surface, a {{domxref("Element/pointerup_event", "pointerup")}} event is sent. We handle this event by calling the `handleEnd()` function below. Its job is to draw the last line segment for the touch that ended and remove the touch point from the ongoing touch list. ```js function handleEnd(evt) { log("pointerup"); const el = document.getElementsByTagName("canvas")[0]; const ctx = el.getContext("2d"); const color = colorForTouch(evt); const idx = ongoingTouchIndexById(evt.pointerId); if (idx >= 0) { ctx.lineWidth = 4; ctx.fillStyle = color; ctx.beginPath(); ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY); ctx.lineTo(evt.clientX, evt.clientY); ctx.fillRect(evt.clientX - 4, evt.clientY - 4, 8, 8); // and a square at the end ongoingTouches.splice(idx, 1); // remove it; we're done } else { log("can't figure out which touch to end"); } } ``` This is very similar to the previous function; the only real differences are that we draw a small square to mark the end and that when we call [`Array.splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), we remove the old entry from the ongoing touch list, without adding in the updated information. The result is that we stop tracking that touch point. #### Handling canceled touches If the user's finger wanders into browser UI, or the touch otherwise needs to be canceled, the {{domxref("Element/pointercancel_event", "pointercancel")}} event is sent, and we call the `handleCancel()` function below. ```js function handleCancel(evt) { log(`pointercancel: id = ${evt.pointerId}`); const idx = ongoingTouchIndexById(evt.pointerId); ongoingTouches.splice(idx, 1); // remove it; we're done } ``` Since the idea is to immediately abort the touch, we remove it from the ongoing touch list without drawing a final line segment. ### Convenience functions This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear. #### Selecting a color for each touch In order to make each touch's drawing look different, the `colorForTouch()` function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches. ```js function colorForTouch(touch) { let r = touch.pointerId % 16; let g = Math.floor(touch.pointerId / 3) % 16; let b = Math.floor(touch.pointerId / 7) % 16; r = r.toString(16); // make it a hex digit g = g.toString(16); // make it a hex digit b = b.toString(16); // make it a hex digit const color = `#${r}${g}${b}`; log(`color for touch with identifier ${touch.pointerId} = ${color}`); return color; } ``` The result from this function is a string that can be used when calling {{HTMLElement("canvas")}} functions to set drawing colors. For example, for a {{domxref("PointerEvent.pointerId")}} value of 10, the resulting string is "#aaa". #### Copying a touch object Some browsers may re-use touch objects between events, so it's best to copy the bits you care about, rather than referencing the entire object. ```js function copyTouch(touch) { return { identifier: touch.pointerId, pageX: touch.clientX, pageY: touch.clientY, }; } ``` #### Finding an ongoing touch The `ongoingTouchIndexById()` function below scans through the `ongoingTouches` array to find the touch matching the given identifier, then returns that touch's index into the array. ```js function ongoingTouchIndexById(idToFind) { for (let i = 0; i < ongoingTouches.length; i++) { const id = ongoingTouches[i].identifier; if (id === idToFind) { return i; } } return -1; // not found } ``` #### Showing what's going on ```js function log(msg) { const p = document.getElementById("log"); p.innerHTML = `${msg}\n${p.innerHTML}`; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Pointer events](/en-US/docs/Web/API/Pointer_events) - [Touch events](/en-US/docs/Web/API/Touch_events)
0
data/mdn-content/files/en-us/web/api/pointer_events
data/mdn-content/files/en-us/web/api/pointer_events/multi-touch_interaction/index.md
--- title: Multi-touch interaction slug: Web/API/Pointer_events/Multi-touch_interaction page-type: guide --- {{DefaultAPISidebar("Pointer Events")}} Pointer events extend DOM input events to support various pointing input devices such as pen/stylus and touch screens as well as mouse. The _pointer_ is a hardware-agnostic device that can target a specific set of screen coordinates. Having a single event model for pointers can simplify creating websites, applications and provide a good user experience regardless of the user's hardware. Pointer events have many similarities to mouse events but they support multiple simultaneous pointers such as multiple fingers on a touch screen. This additional feature can be used to provide richer user interaction models but at the cost of additional complexity in the multi-touch interaction handling. This document demonstrates via example code, using pointer events with different multi-touch interactions. A _live_ version of this application is available on [GitHub](https://mdn.github.io/dom-examples/pointerevents/Multi-touch_interaction.html). The [source code is available on GitHub](https://github.com/mdn/dom-examples/blob/main/pointerevents/Multi-touch_interaction.html); pull requests and [bug reports](https://github.com/mdn/dom-examples/issues) are welcome. ## Example This example demonstrates using pointer events' various event types ({{domxref("Element/pointerdown_event", "pointerdown")}}, {{domxref("Element/pointermove_event", "pointermove")}}, {{domxref("Element/pointerup_event", "pointerup")}} {{domxref("Element/pointercancel_event", "pointercancel")}}, etc.) for different multi-touch interactions. ### Define touch targets The application uses {{HTMLElement("div")}} to define three different touch target areas. ```html <style> div { margin: 0em; padding: 2em; } #target1 { background: white; border: 1px solid black; } #target2 { background: white; border: 1px solid black; } #target3 { background: white; border: 1px solid black; } </style> ``` ### Global state To support multi-touch interaction, preserving a pointer's event state during various event phases is required. This application uses three arrays to cache event state, one cache per target element. ```js // Log events flag const logEvents = false; // Event caches, one per touch target const evCache1 = []; const evCache2 = []; const evCache3 = []; ``` ### Register event handlers Event handlers are registered for the following pointer events: {{domxref("Element/pointerdown_event", "pointerdown")}}, {{domxref("Element/pointermove_event", "pointermove")}} and {{domxref("Element/pointerup_event", "pointerup")}}. The handler for {{domxref("Element/pointerup_event", "pointerup")}} is used for the {{domxref("Element/pointercancel_event", "pointercancel")}}, {{domxref("Element/pointerout_event", "pointerout")}} and {{domxref("Element/pointerleave_event", "pointerleave")}} events, since these four events have the same semantics in this application. ```js function setHandlers(name) { // Install event handlers for the given element const el = document.getElementById(name); el.onpointerdown = pointerdownHandler; el.onpointermove = pointermoveHandler; // Use same handler for pointer{up,cancel,out,leave} events since // the semantics for these events - in this app - are the same. el.onpointerup = pointerupHandler; el.onpointercancel = pointerupHandler; el.onpointerout = pointerupHandler; el.onpointerleave = pointerupHandler; } function init() { setHandlers("target1"); setHandlers("target2"); setHandlers("target3"); } ``` ### Pointer down The {{domxref("Element/pointerdown_event", "pointerdown")}} event is fired when a pointer (mouse, pen/stylus or touch point on a touchscreen) makes contact with the _contact surface_. The event's state must be cached, in case this down event is part of a multi-touch interaction. In this application, when a pointer is placed down on an element, the background color of the element changes, depending on the number of active touch points the element has. See the [`update_background`](#update_background_color) function for more details about the color changes. ```js function pointerdownHandler(ev) { // The pointerdown event signals the start of a touch interaction. // Save this event for later processing (this could be part of a // multi-touch interaction) and update the background color pushEvent(ev); if (logEvents) { log(`pointerDown: name = ${ev.target.id}`, ev); } updateBackground(ev); } ``` ### Pointer move The {{domxref("Element/pointermove_event", "pointermove")}} handler is called when the pointer moves. It may be called multiple times (for example, if the user moves the pointer) before a different event type is fired. In this application, a pointer move is represented by the target's border being set to `dashed` to provide a clear visual indication that the element has received this event. ```js function pointermoveHandler(ev) { // Note: if the user makes more than one "simultaneous" touch, most browsers // fire at least one pointermove event and some will fire several pointermoves. // // This function sets the target element's border to "dashed" to visually // indicate the target received a move event. if (logEvents) { log("pointerMove", ev); } updateBackground(ev); ev.target.style.border = "dashed"; } ``` ### Pointer up The {{domxref("Element/pointerup_event", "pointerup")}} event is fired when a pointer is raised from the _contact surface_. When this occurs, the event is removed from the associated event cache. In this application, this handler is also used for {{domxref("Element/pointercancel_event", "pointercancel")}}, {{domxref("Element/pointerleave_event", "pointerleave")}} and {{domxref("Element/pointerout_event", "pointerout")}} events. ```js function pointerupHandler(ev) { if (logEvents) { log(ev.type, ev); } // Remove this touch point from the cache and reset the target's // background and border removeEvent(ev); updateBackground(ev); ev.target.style.border = "1px solid black"; } ``` ### Application UI The application uses {{HTMLElement("div")}} elements for the touch areas and provides buttons to enable logging and to clear the log. To prevent the browser's default touch behavior from overriding this application's pointer handling, the {{cssxref("touch-action")}} property is applied to the {{HTMLElement("body")}} element. ```html <body onload="init();" style="touch-action:none"> <div id="target1">Tap, Hold or Swipe me 1</div> <div id="target2">Tap, Hold or Swipe me 2</div> <div id="target3">Tap, Hold or Swipe me 3</div> <!-- UI for logging/debugging --> <button id="log" onclick="enableLog(event);">Start/Stop event logging</button> <button id="clearlog" onclick="clearLog(event);">Clear the log</button> <p></p> <output></output> </body> ``` ### Miscellaneous functions These functions support the application but aren't directly involved with the event flow. #### Cache management These functions manage the global event caches `evCache1`, `evCache2` and `evCache3`. ```js function getCache(ev) { // Return the cache for this event's target element switch (ev.target.id) { case "target1": return evCache1; case "target2": return evCache2; case "target3": return evCache3; default: log("Error with cache handling", ev); } } function pushEvent(ev) { // Save this event in the target's cache const evCache = getCache(ev); evCache.push(ev); } function removeEvent(ev) { // Remove this event from the target's cache const evCache = getCache(ev); const index = evCache.findIndex( (cachedEv) => cachedEv.pointerId === ev.pointerId, ); evCache.splice(index, 1); } ``` #### Update background color The background color of the touch areas will change as follows: no active touches is `white`; one active touch is `yellow`; two simultaneous touches is `pink` and three or more simultaneous touches is `lightblue`. ```js function updateBackground(ev) { // Change background color based on the number of simultaneous touches/pointers // currently down: // white - target element has no touch points i.e. no pointers down // yellow - one pointer down // pink - two pointers down // lightblue - three or more pointers down const evCache = getCache(ev); switch (evCache.length) { case 0: // Target element has no touch points ev.target.style.background = "white"; break; case 1: // Single touch point ev.target.style.background = "yellow"; break; case 2: // Two simultaneous touch points ev.target.style.background = "pink"; break; default: // Three or more simultaneous touches ev.target.style.background = "lightblue"; } } ``` #### Event logging These functions are used send to event activity to the application window (to support debugging and learning about the event flow). ```js // Log events flag let logEvents = false; function enableLog(ev) { logEvents = !logEvents; } function log(name, ev) { const o = document.getElementsByTagName("output")[0]; const s = `${name}:<br>` + ` pointerID = ${ev.pointerId}<br>` + ` pointerType = ${ev.pointerType}<br>` + ` isPrimary = ${ev.isPrimary}`; o.innerHTML += `${s}<br>`; } function clearLog(event) { const o = document.getElementsByTagName("output")[0]; o.innerHTML = ""; } ```
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/oscillatornode/index.md
--- title: OscillatorNode slug: Web/API/OscillatorNode page-type: web-api-interface browser-compat: api.OscillatorNode --- {{APIRef("Web Audio API")}} The **`OscillatorNode`** interface represents a periodic waveform, such as a sine wave. It is an {{domxref("AudioScheduledSourceNode")}} audio-processing module that causes a specified frequency of a given wave to be createdβ€”in effect, a constant tone. {{InheritanceDiagram}} <table class="properties"> <tbody> <tr> <th scope="row">Number of inputs</th> <td><code>0</code></td> </tr> <tr> <th scope="row">Number of outputs</th> <td><code>1</code></td> </tr> <tr> <th scope="row">Channel count mode</th> <td><code>max</code></td> </tr> <tr> <th scope="row">Channel count</th> <td><code>2</code> (not used in the default count mode)</td> </tr> <tr> <th scope="row">Channel interpretation</th> <td><code>speakers</code></td> </tr> </tbody> </table> ## Constructor - {{domxref("OscillatorNode.OscillatorNode", "OscillatorNode()")}} - : Creates a new instance of an `OscillatorNode` object, optionally providing an object specifying default values for the node's [properties](#instance_properties). As an alternative, you can use the {{domxref("BaseAudioContext.createOscillator()")}} factory method; see [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode). ## Instance properties _Also inherits properties from its parent, {{domxref("AudioScheduledSourceNode")}}._ - {{domxref("OscillatorNode.frequency")}} - : An [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} representing the frequency of oscillation in hertz (though the `AudioParam` returned is read-only, the value it represents is not). The default value is 440 Hz (a standard middle-A note). - {{domxref("OscillatorNode.detune")}} - : An [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} representing detuning of oscillation in cents (though the `AudioParam` returned is read-only, the value it represents is not). The default value is 0. - {{domxref("OscillatorNode.type")}} - : A string which specifies the shape of waveform to play; this can be one of a number of standard values, or `custom` to use a {{domxref("PeriodicWave")}} to describe a custom waveform. Different waves will produce different tones. Standard values are `"sine"`, `"square"`, `"sawtooth"`, `"triangle"` and `"custom"`. The default is `"sine"`. ## Instance methods _Also inherits methods from its parent, {{domxref("AudioScheduledSourceNode")}}._ - {{domxref("OscillatorNode.setPeriodicWave()")}} - : Sets a {{domxref("PeriodicWave")}} which describes a periodic waveform to be used instead of one of the standard waveforms; calling this sets the `type` to `custom`. - {{domxref("AudioScheduledSourceNode.start()")}} - : Specifies the exact time to start playing the tone. - {{domxref("AudioScheduledSourceNode.stop()")}} - : Specifies the time to stop playing the tone. ## Events _Also inherits events from its parent, {{domxref("AudioScheduledSourceNode")}}._ ## Examples The following example shows basic usage of an {{domxref("AudioContext")}} to create an oscillator node and to start playing a tone on it. For an applied example, check out our [Violent Theremin demo](https://mdn.github.io/webaudio-examples/violent-theremin/) ([see app.js](https://github.com/mdn/webaudio-examples/blob/main/violent-theremin/scripts/app.js) for relevant code). ```js // create web audio api context const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // create Oscillator node const oscillator = audioCtx.createOscillator(); oscillator.type = "square"; oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz oscillator.connect(audioCtx.destination); oscillator.start(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/oscillatornode
data/mdn-content/files/en-us/web/api/oscillatornode/setperiodicwave/index.md
--- title: "OscillatorNode: setPeriodicWave() method" short-title: setPeriodicWave() slug: Web/API/OscillatorNode/setPeriodicWave page-type: web-api-instance-method browser-compat: api.OscillatorNode.setPeriodicWave --- {{ APIRef("Web Audio API") }} The **`setPeriodicWave()`** method of the {{ domxref("OscillatorNode") }} interface is used to point to a {{domxref("PeriodicWave")}} defining a periodic waveform that can be used to shape the oscillator's output, when {{domxref("OscillatorNode.type", "type")}} is `custom`. ## Syntax ```js-nolint setPeriodicWave(wave) ``` ### Parameters - `wave` - : A {{domxref("PeriodicWave")}} object representing the waveform to use as the shape of the oscillator's output. ### Return value None ({{jsxref("undefined")}}). ## Examples The following example illustrates simple usage of `createPeriodicWave()`, recreating a sine wave from a periodic wave. ```js const real = new Float32Array(2); const imag = new Float32Array(2); const ac = new AudioContext(); const osc = ac.createOscillator(); real[0] = 0; imag[0] = 0; real[1] = 1; imag[1] = 0; const wave = ac.createPeriodicWave(real, imag); osc.setPeriodicWave(wave); osc.connect(ac.destination); osc.start(); osc.stop(2); ``` This works because a sound that contains only a fundamental tone is by definition a sine wave. Here, we create a {{domxref("PeriodicWave")}} with two values. The first value is the DC offset, which is the value at which the oscillator starts. 0 is good here, because we want to start the curve at the middle of the \[-1.0; 1.0] range. The second and subsequent values are sine and cosine components. You can think of it as the result of a Fourier transform, where you get frequency domain values from time domain value. Here, with `createPeriodicWave()`, you specify the frequencies, and the browser performs an inverse Fourier transform to get a time domain buffer for the frequency of the oscillator. Here, we only set one component at full volume (1.0) on the fundamental tone, so we get a sine wave. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API) - [AudioContext.createPeriodicWave](/en-US/docs/Web/API/BaseAudioContext/createPeriodicWave)
0
data/mdn-content/files/en-us/web/api/oscillatornode
data/mdn-content/files/en-us/web/api/oscillatornode/frequency/index.md
--- title: "OscillatorNode: frequency property" short-title: frequency slug: Web/API/OscillatorNode/frequency page-type: web-api-instance-property browser-compat: api.OscillatorNode.frequency --- {{ APIRef("Web Audio API") }} The **`frequency`** property of the {{ domxref("OscillatorNode") }} interface is an [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} representing the frequency of oscillation in hertz. > **Note:** though the `AudioParam` returned is read-only, the value it represents is not. ## Value An [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}}. ## Examples The following example shows basic usage of an {{ domxref("AudioContext") }} to create an oscillator node. For an applied example, check out our [Violent Theremin demo](https://mdn.github.io/webaudio-examples/violent-theremin/) ([see app.js](https://github.com/mdn/webaudio-examples/blob/main/violent-theremin/scripts/app.js) for relevant code). ```js // create web audio api context const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // create Oscillator node const oscillator = audioCtx.createOscillator(); oscillator.type = "square"; oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz oscillator.start(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/oscillatornode
data/mdn-content/files/en-us/web/api/oscillatornode/detune/index.md
--- title: "OscillatorNode: detune property" short-title: detune slug: Web/API/OscillatorNode/detune page-type: web-api-instance-property browser-compat: api.OscillatorNode.detune --- {{ APIRef("Web Audio API") }} The `detune` property of the {{ domxref("OscillatorNode") }} interface is an [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}} representing detuning of oscillation in [cents](https://en.wikipedia.org/wiki/Cent_%28music%29). > **Note:** though the `AudioParam` returned is read-only, the value it represents is not. ## Value An [a-rate](/en-US/docs/Web/API/AudioParam#a-rate) {{domxref("AudioParam")}}. ## Examples The following example shows basic usage of an {{ domxref("AudioContext") }} to create an oscillator node. For applied examples/information, check out our [Violent Theremin demo](https://mdn.github.io/webaudio-examples/violent-theremin/) ([see app.js](https://github.com/mdn/webaudio-examples/blob/main/violent-theremin/scripts/app.js) for relevant code). ```js // create web audio api context const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // create Oscillator node const oscillator = audioCtx.createOscillator(); oscillator.type = "square"; oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz oscillator.detune.setValueAtTime(100, audioCtx.currentTime); // value in cents oscillator.start(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/oscillatornode
data/mdn-content/files/en-us/web/api/oscillatornode/type/index.md
--- title: "OscillatorNode: type property" short-title: type slug: Web/API/OscillatorNode/type page-type: web-api-instance-property browser-compat: api.OscillatorNode.type --- {{ APIRef("Web Audio API") }} The **`type`** property of the {{ domxref("OscillatorNode") }} interface specifies what shape of [waveform](https://en.wikipedia.org/wiki/Waveform) the oscillator will output. There are several common waveforms available, as well as an option to specify a custom waveform shape. The shape of the waveform will affect the tone that is produced. ## Value A string specifying the shape of oscillator wave. The different available values are: - `sine` - : A [sine wave](https://en.wikipedia.org/wiki/Sine_wave). This is the default value. - `square` - : A [square wave](https://en.wikipedia.org/wiki/Square_wave) with a [duty cycle](https://en.wikipedia.org/wiki/Duty_cycle) of 0.5; that is, the signal is "high" for half of each period. - `sawtooth` - : A [sawtooth wave](https://en.wikipedia.org/wiki/Sawtooth_wave). - `triangle` - : A [triangle wave](https://en.wikipedia.org/wiki/Triangle_wave). - `custom` - : A custom waveform. You never set `type` to `custom` manually; instead, use the {{domxref("OscillatorNode.setPeriodicWave", "setPeriodicWave()")}} method to provide the data representing the waveform. Doing so automatically sets the `type` to `custom`. ### Exceptions - `InvalidStateError` {{domxref("DOMException")}} - : Thrown if the value `custom` was specified. To set a custom waveform, just call {{domxref("OscillatorNode.setPeriodicWave", "setPeriodicWave()")}}. Doing so automatically sets the type for you. ## Examples The following example shows basic usage of an {{ domxref("AudioContext") }} to create an oscillator node. For an applied example, check out our [Violent Theremin demo](https://mdn.github.io/webaudio-examples/violent-theremin/) ([see app.js](https://github.com/mdn/webaudio-examples/blob/main/violent-theremin/scripts/app.js) for relevant code). ```js // create web audio api context const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // create Oscillator node const oscillator = audioCtx.createOscillator(); oscillator.type = "square"; oscillator.frequency.setValueAtTime(440, audioCtx.currentTime); // value in hertz oscillator.start(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Audio API](/en-US/docs/Web/API/Web_Audio_API/Using_Web_Audio_API)
0
data/mdn-content/files/en-us/web/api/oscillatornode
data/mdn-content/files/en-us/web/api/oscillatornode/oscillatornode/index.md
--- title: "OscillatorNode: OscillatorNode() constructor" short-title: OscillatorNode() slug: Web/API/OscillatorNode/OscillatorNode page-type: web-api-constructor browser-compat: api.OscillatorNode.OscillatorNode --- {{APIRef("Web Audio API")}} The **`OscillatorNode()`** constructor of the [Web Audio API](/en-US/docs/Web/API/Web_Audio_API) creates a new {{domxref("OscillatorNode")}} object which is an {{domxref("AudioNode")}} that represents a periodic waveform, like a sine wave, optionally setting the node's properties' values to match values in a specified object. If the default values of the properties are acceptable, you can optionally use the {{domxref("BaseAudioContext.createOscillator()")}} factory method instead; see [Creating an AudioNode](/en-US/docs/Web/API/AudioNode#creating_an_audionode). ## Syntax ```js-nolint new OscillatorNode(context, options) ``` ### Parameters - `context` - : A reference to an {{domxref("AudioContext")}}. - `options` {{optional_inline}} - : An object whose properties specify the initial values for the oscillator node's properties. Any properties omitted from the object will take on the default value as documented. - `type` - : The shape of the wave produced by the node. Valid values are '`sine`', '`square`', '`sawtooth`', '`triangle`' and '`custom`'. The default is '`sine`'. - `detune` - : A detuning value (in cents) which will offset the `frequency` by the given amount. Its default is 0. - `frequency` - : The frequency (in [hertz](https://en.wikipedia.org/wiki/Hertz)) of the periodic waveform. Its default is 440. - `periodicWave` - : An arbitrary period waveform described by a {{domxref("PeriodicWave")}} object. - `channelCount` - : Represents an integer used to determine how many channels are used when [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) connections to any inputs to the node. (See {{domxref("AudioNode.channelCount")}} for more information.) Its usage and precise definition depend on the value of `channelCountMode`. - `channelCountMode` - : Represents an enumerated value describing the way channels must be matched between the node's inputs and outputs. (See {{domxref("AudioNode.channelCountMode")}} for more information including default values.) - `channelInterpretation` - : Represents an enumerated value describing the meaning of the channels. This interpretation will define how audio [up-mixing and down-mixing](/en-US/docs/Web/API/Web_Audio_API/Basic_concepts_behind_Web_Audio_API#up-mixing_and_down-mixing) will happen. The possible values are `"speakers"` or `"discrete"`. (See {{domxref("AudioNode.channelCountMode")}} for more information including default values.) ### Return value A new {{domxref("OscillatorNode")}} object instance. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/mousescrollevent/index.md
--- title: MouseScrollEvent slug: Web/API/MouseScrollEvent page-type: web-api-interface status: - deprecated - non-standard browser-compat: api.MouseScrollEvent --- {{APIRef("UI Events")}}{{ Non-standard_Header }}{{Deprecated_Header}} The **`MouseScrollEvent`** interface represents events that occur due to the user moving a mouse wheel or similar input device. > **Warning:** Do not use this interface for wheel events. > > Like `MouseWheelEvent`, this interface is non-standard and deprecated. It was used in Gecko-based browsers only. Instead use the standard _{{domxref("WheelEvent")}}._ ## Method overview ```webidl void initMouseScrollEvent( in DOMString typeArg, in boolean canBubbleArg, in boolean cancelableArg, in nsIDOMAbstractView viewArg, in long detailArg, in long screenXArg, in long screenYArg, in long clientXArg, in long clientYArg, in boolean ctrlKeyArg, in boolean altKeyArg, in boolean shiftKeyArg, in boolean metaKeyArg, in unsigned short buttonArg, in nsIDOMEventTarget relatedTargetArg, in long axis); ``` ## Attributes | Attribute | Type | Description | | ------------------------- | ------ | --------------------------- | | `axis` {{ReadOnlyInline}} | `long` | Indicates scroll direction. | ## Constants ### Delta modes | Constant | Value | Description | | ----------------- | ------ | -------------------------------------------------- | | `HORIZONTAL_AXIS` | `0x01` | The event is caused by horizontal wheel operation. | | `VERTICAL_AXIS` | `0x02` | The event is caused by vertical wheel operation. | ## Instance methods - `initMouseScrollEvent()` - : See `nsIDOMMouseScrollEvent::initMouseScrollEvent()`. ## Browser compatibility {{Compat}} ## See also - `DOMMouseScroll` - `MozMousePixelScroll` - Standardized mouse wheel event object: {{ domxref("WheelEvent") }}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/performanceelementtiming/index.md
--- title: PerformanceElementTiming slug: Web/API/PerformanceElementTiming page-type: web-api-interface status: - experimental browser-compat: api.PerformanceElementTiming --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`PerformanceElementTiming`** interface contains render timing information for image and text node elements the developer annotated with an [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute for observation. ## Description The aim of the Element Timing API is to give web developers or analytics tools the ability to measure rendering timestamps of critical elements on a page. The API supports timing information on the following elements: - {{htmlelement("img")}} elements, - {{SVGElement("image")}} elements inside an {{SVGElement("svg")}}, - [poster](/en-US/docs/Web/HTML/Element/video#poster) images of {{htmlelement("video")}} elements, - elements which have a {{cssxref("background-image")}}, and - groups of text nodes, such as a {{htmlelement("p")}}. The author flags an element for observation by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute on the element. `PerformanceElementTiming` inherits from {{domxref("PerformanceEntry")}}. {{InheritanceDiagram}} ## Instance properties This interface extends the following {{domxref("PerformanceEntry")}} properties for event timing performance entry types by qualifying them as follows: - {{domxref("PerformanceEntry.duration")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Always returns `0` as `duration` does not apply to this interface. - {{domxref("PerformanceEntry.entryType")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Always returns `"element"`. - {{domxref("PerformanceEntry.name")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns `"image-paint"` for images and `"text-paint"` for text. - {{domxref("PerformanceEntry.startTime")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : Returns the value of this entry's {{domxref("PerformanceElementTiming.renderTime", "renderTime")}} if it is not `0`, otherwise the value of this entry's {{domxref("PerformanceElementTiming.loadTime", "loadTime")}}. This interface also supports the following properties: - {{domxref("PerformanceElementTiming.element")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : An {{domxref("Element")}} representing the element we are returning information about. - {{domxref("PerformanceElementTiming.id")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : A string which is the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) of the element. - {{domxref("PerformanceElementTiming.identifier")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : A string which is the value of the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/for) attribute on the element. - {{domxref("PerformanceElementTiming.intersectionRect")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : A {{domxref("DOMRectReadOnly")}} which is the rectangle of the element within the viewport. - {{domxref("PerformanceElementTiming.loadTime")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : A {{domxref("DOMHighResTimeStamp")}} with the loadTime of the element. - {{domxref("PerformanceElementTiming.naturalHeight")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : An unsigned 32-bit integer (unsigned long) which is the intrinsic height of the image if this is applied to an image, 0 for text. - {{domxref("PerformanceElementTiming.naturalWidth")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : An unsigned 32-bit integer (unsigned long) which is the intrinsic width of the image if this is applied to an image, 0 for text. - {{domxref("PerformanceElementTiming.renderTime")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : A {{domxref("DOMHighResTimeStamp")}} with the renderTime of the element. - {{domxref("PerformanceElementTiming.url")}} {{ReadOnlyInline}} {{Experimental_Inline}} - : A string which is the initial URL of the resources request for images, 0 for text. ## Instance methods - {{domxref("PerformanceElementTiming.toJSON()")}} {{Experimental_Inline}} - : Returns a JSON representation of the `PerformanceElementTiming` object. ## Examples ### Observing render time of specific elements In this example two elements are being observed by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A {{domxref("PerformanceObserver")}} is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. ```html <img src="image.jpg" elementtiming="big-image" /> <p elementtiming="text" id="text-id">text here</p> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { console.log(entry); }); }); observer.observe({ type: "element", buffered: true }); ``` Two entries will be output to the console. The first containing details of the image, the second with details of the text node. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) HTML attribute
0
data/mdn-content/files/en-us/web/api/performanceelementtiming
data/mdn-content/files/en-us/web/api/performanceelementtiming/naturalwidth/index.md
--- title: "PerformanceElementTiming: naturalWidth property" short-title: naturalWidth slug: Web/API/PerformanceElementTiming/naturalWidth page-type: web-api-instance-property status: - experimental browser-compat: api.PerformanceElementTiming.naturalWidth --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`naturalWidth`** read-only property of the {{domxref("PerformanceElementTiming")}} interface returns the intrinsic width of the image element. ## Value An unsigned 32-bit integer (unsigned long) which is the intrinsic width of the image if this is applied to an image, `0` for text. ## Examples ### Logging `naturalWidth` In this example an {{HTMLElement("image")}} element is being observed by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A {{domxref("PerformanceObserver")}} is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. The image file has a width of 1000px and a height of 750px. Calling `entry.naturalWidth` returns `1000`, that being the intrinsic width in pixels. ```html <img src="image.jpg" alt="a nice image" elementtiming="big-image" id="myImage" /> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.identifier === "big-image") { console.log(entry.naturalWidth); } }); }); observer.observe({ type: "element", buffered: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceelementtiming
data/mdn-content/files/en-us/web/api/performanceelementtiming/element/index.md
--- title: "PerformanceElementTiming: element property" short-title: element slug: Web/API/PerformanceElementTiming/element page-type: web-api-instance-property status: - experimental browser-compat: api.PerformanceElementTiming.element --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`element`** read-only property of the {{domxref("PerformanceElementTiming")}} interface returns an {{domxref("Element")}} which is a pointer to the observed element. ## Value An {{domxref("Element")}}, or [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) if the element is a [shadow DOM](/en-US/docs/Web/API/Web_components/Using_shadow_DOM) element. ## Examples ### Logging the observed element In this example an {{HTMLElement("img")}} element is being observed by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A {{domxref("PerformanceObserver")}} is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. The DOM element that is observed is logged to the console. ```html <img src="image.jpg" alt="a nice image" elementtiming="big-image" /> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.identifier === "big-image") { console.log(entry.element); } }); }); observer.observe({ type: "element", buffered: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceelementtiming
data/mdn-content/files/en-us/web/api/performanceelementtiming/rendertime/index.md
--- title: "PerformanceElementTiming: renderTime property" short-title: renderTime slug: Web/API/PerformanceElementTiming/renderTime page-type: web-api-instance-property status: - experimental browser-compat: api.PerformanceElementTiming.renderTime --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`renderTime`** read-only property of the {{domxref("PerformanceElementTiming")}} interface returns the render time of the associated element. ## Value A {{domxref("DOMHighResTimeStamp")}} with the render time of the element. For images this will be the **image rendering timestamp**. This is defined as the next paint that occurs after the image becomes fully loaded. If the timing allow check fails (as defined by the [Timing-allow-origin](/en-US/docs/Web/HTTP/Headers/Timing-Allow-Origin) header) this will return `0`. For text nodes this will be the **text rendering timestamp**. This is defined as when the element becomes text painted. ## Examples ### Logging `renderTime` In this example an {{HTMLElement("image")}} element is being observed by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A {{domxref("PerformanceObserver")}} is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. Calling `entry.renderTime` returns the render time of the image element. ```html <img src="image.jpg" alt="a nice image" elementtiming="big-image" id="myImage" /> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.identifier === "big-image") { console.log(entry.renderTime); } }); }); observer.observe({ type: "element", buffered: true }); ``` ### Cross-origin image render time For security reasons, the value of the `renderTime` property is `0` if the resource is a cross-origin request. 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 `renderTime` if it is not `0`, and otherwise the value of this entry's {{domxref("PerformanceElementTiming.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 isRenderTime = entry.renderTime ? true : false; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceelementtiming
data/mdn-content/files/en-us/web/api/performanceelementtiming/loadtime/index.md
--- title: "PerformanceElementTiming: loadTime property" short-title: loadTime slug: Web/API/PerformanceElementTiming/loadTime page-type: web-api-instance-property status: - experimental browser-compat: api.PerformanceElementTiming.loadTime --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`loadTime`** read-only property of the {{domxref("PerformanceElementTiming")}} interface always returns `0` for text. For images it returns the time which is the latest between the time the image resource is loaded and the time it is attached to the element. ## Value A {{domxref("DOMHighResTimeStamp")}} with the `loadTime` of the element. Always `0` for text. ## Examples ### Logging `loadTime` In this example an {{HTMLElement("img")}} element is being observed by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A {{domxref("PerformanceObserver")}} is registered to get all performance entries of type `"element"`. The `buffered` flag is used to access data from before the observer was created. Calling `entry.loadTime` returns the loadTime of the image element. ```html <img src="image.jpg" alt="a nice image" elementtiming="big-image" id="myImage" /> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.identifier === "big-image") { console.log(entry.loadTime); } }); }); observer.observe({ type: "element", buffered: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceelementtiming
data/mdn-content/files/en-us/web/api/performanceelementtiming/naturalheight/index.md
--- title: "PerformanceElementTiming: naturalHeight property" short-title: naturalHeight slug: Web/API/PerformanceElementTiming/naturalHeight page-type: web-api-instance-property status: - experimental browser-compat: api.PerformanceElementTiming.naturalHeight --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`naturalHeight`** read-only property of the {{domxref("PerformanceElementTiming")}} interface returns the intrinsic height of the image element. ## Value An unsigned 32-bit integer (unsigned long) which is the intrinsic height of the image if this is applied to an image, `0` for text. ## Examples ### Logging `naturalHeight` In this example an {{HTMLElement("image")}} element is being observed by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A {{domxref("PerformanceObserver")}} is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. The image file has a width of 1000px and a height of 750px. Calling `entry.naturalHeight` returns `750`, that being the intrinsic height in pixels. ```html <img src="image.jpg" alt="a nice image" elementtiming="big-image" id="myImage" /> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.identifier === "big-image") { console.log(entry.naturalHeight); } }); }); observer.observe({ type: "element", buffered: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceelementtiming
data/mdn-content/files/en-us/web/api/performanceelementtiming/identifier/index.md
--- title: "PerformanceElementTiming: identifier property" short-title: identifier slug: Web/API/PerformanceElementTiming/identifier page-type: web-api-instance-property status: - experimental browser-compat: api.PerformanceElementTiming.identifier --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`identifier`** read-only property of the {{domxref("PerformanceElementTiming")}} interface returns the value of the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute on the element. ## Value A string. ## Examples ### Using `identifier` In this example an {{HTMLElement("img")}} element is being observed by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A {{domxref("PerformanceObserver")}} is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. The value of [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) is `big-image`. Calling `entry.identifier` therefore returns the string `big-image`. ```html <img src="image.jpg" alt="a nice image" elementtiming="big-image" id="myImage" /> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.identifier === "big-image") { console.log(entry.naturalWidth); } }); }); observer.observe({ type: "element", buffered: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceelementtiming
data/mdn-content/files/en-us/web/api/performanceelementtiming/url/index.md
--- title: "PerformanceElementTiming: url property" short-title: url slug: Web/API/PerformanceElementTiming/url page-type: web-api-instance-property status: - experimental browser-compat: api.PerformanceElementTiming.url --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`url`** read-only property of the {{domxref("PerformanceElementTiming")}} interface returns the initial URL of the resource request when the element is an image. ## Value A string which is the initial URL of the resources request for images or `0` for text. ## Examples ### Logging `url` In this example an {{HTMLElement("img")}} element is being observed by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A {{domxref("PerformanceObserver")}} is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. Calling `entry.url` returns `https://example.com/image.jpg`. ```html <img src="https://example.com/image.jpg" alt="a nice image" elementtiming="big-image" id="myImage" /> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.identifier === "big-image") { console.log(entry.url); } }); }); observer.observe({ type: "element", buffered: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceelementtiming
data/mdn-content/files/en-us/web/api/performanceelementtiming/id/index.md
--- title: "PerformanceElementTiming: id property" short-title: id slug: Web/API/PerformanceElementTiming/id page-type: web-api-instance-property status: - experimental browser-compat: api.PerformanceElementTiming.id --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`id`** read-only property of the {{domxref("PerformanceElementTiming")}} interface returns the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) of the associated element. ## Value A string. ## Examples ### Using `id` In this example an {{HTMLElement("img")}} element is being observed by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A {{domxref("PerformanceObserver")}} is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. It will log `myImage` to the console, this being the [`id`](/en-US/docs/Web/HTML/Global_attributes#id) of the image element. ```html <img src="image.jpg" alt="a nice image" elementtiming="big-image" id="myImage" /> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.identifier === "big-image") { console.log(entry.id); } }); }); observer.observe({ type: "element", buffered: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceelementtiming
data/mdn-content/files/en-us/web/api/performanceelementtiming/intersectionrect/index.md
--- title: "PerformanceElementTiming: intersectionRect property" short-title: intersectionRect slug: Web/API/PerformanceElementTiming/intersectionRect page-type: web-api-instance-property status: - experimental browser-compat: api.PerformanceElementTiming.intersectionRect --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`intersectionRect`** read-only property of the {{domxref("PerformanceElementTiming")}} interface returns the rectangle of the element within the viewport. ## Value A {{domxref("DOMRectReadOnly")}} which is the rectangle of the element within the viewport. For display images this is the display rectangle of the image within the viewport. For text this is the display rectangle of the node in the viewport. This being the smallest rectangle that contains the union of all text nodes that belong to the element. ## Examples ### Logging `intersectionRect` In this example an {{HTMLElement("img")}} element is being observed by adding the [`elementtiming`](/en-US/docs/Web/HTML/Attributes/elementtiming) attribute. A {{domxref("PerformanceObserver")}} is registered to get all performance entries of type `"element"` and the `buffered` flag is used to access data from before observer creation. Calling `entry.intersectionRect` returns a {{domxref("DOMRectReadOnly")}} object with the display rectangle of the image. ```html <img src="image.jpg" alt="a nice image" elementtiming="big-image" id="myImage" /> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.identifier === "big-image") { console.log(entry.intersectionRect); } }); }); observer.observe({ type: "element", buffered: true }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/performanceelementtiming
data/mdn-content/files/en-us/web/api/performanceelementtiming/tojson/index.md
--- title: "PerformanceElementTiming: toJSON() method" short-title: toJSON() slug: Web/API/PerformanceElementTiming/toJSON page-type: web-api-instance-method status: - experimental browser-compat: api.PerformanceElementTiming.toJSON --- {{APIRef("Performance API")}}{{SeeCompatTable}} The **`toJSON()`** method of the {{domxref("PerformanceElementTiming")}} interface is a {{Glossary("Serialization","serializer")}}; it returns a JSON representation of the {{domxref("PerformanceElementTiming")}} object. ## Syntax ```js-nolint toJSON() ``` ### Parameters None. ### Return value A {{jsxref("JSON")}} object that is the serialization of the {{domxref("PerformanceElementTiming")}} object. The JSON doesn't contain the {{domxref("PerformanceElementTiming.element", "element")}} property because it is of type {{domxref("Element")}}, which doesn't provide a `toJSON()` operation. The {{domxref("PerformanceElementTiming.id", "id")}} of the element is provided, though. ## Examples ### Using the toJSON method In this example, calling `entry.toJSON()` returns a JSON representation of the `PerformanceElementTiming` object, with the information about the image element. ```html <img src="image.jpg" alt="a nice image" elementtiming="big-image" id="myImage" /> ``` ```js const observer = new PerformanceObserver((list) => { list.getEntries().forEach((entry) => { if (entry.identifier === "big-image") { console.log(entry.toJSON()); } }); }); observer.observe({ type: "element", buffered: true }); ``` This would log a JSON object like so: ```json { "name": "image-paint", "entryType": "element", "startTime": 670894.1000000238, "duration": 0, "renderTime": 0, "loadTime": 670894.1000000238, "intersectionRect": { "x": 299, "y": 76, "width": 135, "height": 155, "top": 76, "right": 434, "bottom": 231, "left": 299 }, "identifier": "big-image", "naturalWidth": 135, "naturalHeight": 155, "id": "myImage", "url": "https://en.wikipedia.org/static/images/project-logos/enwiki.png" } ``` 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/writablestream/index.md
--- title: WritableStream slug: Web/API/WritableStream page-type: web-api-interface browser-compat: api.WritableStream --- {{APIRef("Streams")}} The **`WritableStream`** interface of the [Streams API](/en-US/docs/Web/API/Streams_API) provides a standard abstraction for writing streaming data to a destination, known as a sink. This object comes with built-in backpressure and queuing. `WritableStream` is a [transferable object](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects). ## Constructor - {{domxref("WritableStream.WritableStream", "WritableStream()")}} - : Creates a new `WritableStream` object. ## Instance properties - {{domxref("WritableStream.locked")}} {{ReadOnlyInline}} - : A boolean indicating whether the `WritableStream` is locked to a writer. ## Instance methods - {{domxref("WritableStream.abort()")}} - : Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - {{domxref("WritableStream.close()")}} - : Closes the stream. - {{domxref("WritableStream.getWriter()")}} - : Returns a new instance of {{domxref("WritableStreamDefaultWriter")}} and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Examples The following example illustrates several features of this interface. It shows the creation of the `WritableStream` with a custom sink and an API-supplied queueing strategy. It then calls a function called `sendMessage()`, passing the newly created stream and a string. Inside this function it calls the stream's `getWriter()` method, which returns an instance of {{domxref("WritableStreamDefaultWriter")}}. A `forEach()` call is used to write each chunk of the string to the stream. Finally, `write()` and `close()` return promises that are processed to deal with success or failure of chunks and streams. ```js const list = document.querySelector("ul"); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message); encoded.forEach((chunk) => { defaultWriter.ready .then(() => defaultWriter.write(chunk)) .then(() => { console.log("Chunk written to sink."); }) .catch((err) => { console.log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. defaultWriter.ready .then(() => { defaultWriter.close(); }) .then(() => { console.log("All chunks written"); }) .catch((err) => { console.log("Stream error:", err); }); } const decoder = new TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream( { // Implement the sink write(chunk) { return new Promise((resolve, reject) => { const buffer = new ArrayBuffer(1); const view = new Uint8Array(buffer); view[0] = chunk; const decoded = decoder.decode(view, { stream: true }); const listItem = document.createElement("li"); listItem.textContent = `Chunk decoded: ${decoded}`; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { const listItem = document.createElement("li"); listItem.textContent = `[MESSAGE RECEIVED] ${result}`; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); }, }, queuingStrategy, ); sendMessage("Hello, world.", writableStream); ``` You can find the full code in our [Simple writer example](https://mdn.github.io/dom-examples/streams/simple-writer/). ### Backpressure Because of how [backpressure](/en-US/docs/Web/API/Streams_API/Concepts#backpressure) is supported in the API, its implementation in code may be less than obvious. To see how backpressure is implemented look for three things: - The `highWaterMark` property, which is set when creating the counting strategy (line 35), sets the maximum amount of data that the `WritableStream` instance will handle in a single `write()` operation. In this example, it's the maximum amount of data that can be sent to `defaultWriter.write()` (line 11). - The `defaultWriter.ready` property returns a promise that resolves when the sink (the first property of the `WritableStream` constructor) is done writing data. The data source can either write more data (line 9) or call `close()` (line 24). Calling close() too early can prevent data from being written. This is why the example calls `defaultWriter.ready` twice (lines 9 and 22). - The {{jsxref("Promise")}} returned by the sink's `write()` method (line 40) tells the `WritableStream` and its writer when to resolve `defaultWriter.ready`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [WHATWG Stream Visualizer](https://whatwg-stream-visualizer.glitch.me/), for a basic visualization of readable, writable, and transform streams.
0
data/mdn-content/files/en-us/web/api/writablestream
data/mdn-content/files/en-us/web/api/writablestream/locked/index.md
--- title: "WritableStream: locked property" short-title: locked slug: Web/API/WritableStream/locked page-type: web-api-instance-property browser-compat: api.WritableStream.locked --- {{APIRef("Streams")}} The **`locked`** read-only property of the {{domxref("WritableStream")}} interface returns a boolean indicating whether the `WritableStream` is locked to a writer. ## Value A boolean value indicating whether or not the writable stream is locked. ## Examples ```js const writableStream = new WritableStream( { write(chunk) { // ... }, close() { // ... }, abort(err) { // ... }, }, queuingStrategy, ); // ... const writer = writableStream.getWriter(); writableStream.locked; // should return true, as the stream has been locked to a writer ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/writablestream
data/mdn-content/files/en-us/web/api/writablestream/getwriter/index.md
--- title: "WritableStream: getWriter() method" short-title: getWriter() slug: Web/API/WritableStream/getWriter page-type: web-api-instance-method browser-compat: api.WritableStream.getWriter --- {{APIRef("Streams")}} The **`getWriter()`** method of the {{domxref("WritableStream")}} interface returns a new instance of {{domxref("WritableStreamDefaultWriter")}} and locks the stream to that instance. While the stream is locked, no other writer can be acquired until this one is released. ## Syntax ```js-nolint getWriter() ``` ### Parameters None. ### Return value A {{domxref("WritableStreamDefaultWriter")}} object instance. ### Exceptions - {{jsxref("TypeError")}} - : The stream you are trying to create a writer for is not a {{domxref("WritableStream")}} or it is already locked to another writer. ## Examples The following example illustrates several features of this interface. It shows the creation of the `WritableStream` with a custom sink and an API-supplied queuing strategy. t then calls a function called `sendMessage()`, passing the newly created stream and a string. Inside this function it calls the stream's `getWriter()` method, which returns an instance of {{domxref("WritableStreamDefaultWriter")}}. A `forEach()` call is used to write each chunk of the string to the stream. Finally, `write()` and `close()` return promises that are processed to deal with success or failure of chunks and streams. ```js const list = document.querySelector("ul"); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message, { stream: true }); encoded.forEach((chunk) => { defaultWriter.ready .then(() => defaultWriter.write(chunk)) .then(() => { console.log("Chunk written to sink."); }) .catch((err) => { console.log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. defaultWriter.ready .then(() => { defaultWriter.close(); }) .then(() => { console.log("All chunks written"); }) .catch((err) => { console.log("Stream error:", err); }); } const decoder = new TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream( { // Implement the sink write(chunk) { return new Promise((resolve, reject) => { const buffer = new ArrayBuffer(1); const view = new Uint8Array(buffer); view[0] = chunk; const decoded = decoder.decode(view, { stream: true }); const listItem = document.createElement("li"); listItem.textContent = `Chunk decoded: ${decoded}`; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { const listItem = document.createElement("li"); listItem.textContent = `[MESSAGE RECEIVED] ${result}`; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); }, }, queuingStrategy, ); sendMessage("Hello, world.", writableStream); ``` You can find the full code in our [Simple writer example](https://mdn.github.io/dom-examples/streams/simple-writer/). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/writablestream
data/mdn-content/files/en-us/web/api/writablestream/abort/index.md
--- title: "WritableStream: abort() method" short-title: abort() slug: Web/API/WritableStream/abort page-type: web-api-instance-method browser-compat: api.WritableStream.abort --- {{APIRef("Streams")}} The **`abort()`** method of the {{domxref("WritableStream")}} interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. ## Syntax ```js-nolint abort(reason) ``` ### Parameters - `reason` - : A string providing a human-readable reason for the abort. ### Return value A {{jsxref("Promise")}}, which fulfills with the value given in the `reason` parameter. ### Exceptions - {{jsxref("TypeError")}} - : The stream you are trying to abort is not a {{domxref("WritableStream")}}, or it is locked. ## Examples ```js const writableStream = new WritableStream( { write(chunk) { // ... }, close() { // ... }, abort(err) { // ... }, }, queuingStrategy, ); // ... // abort the stream later on, when required writableStream.abort(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/writablestream
data/mdn-content/files/en-us/web/api/writablestream/close/index.md
--- title: "WritableStream: close() method" short-title: close() slug: Web/API/WritableStream/close page-type: web-api-instance-method browser-compat: api.WritableStream.close --- {{APIRef("Streams")}} The **`close()`** method of the {{domxref("WritableStream")}} interface closes the associated stream. All chunks written before this method is called are sent before the returned promise is fulfilled. This is equivalent to getting a {{domxref("WritableStreamDefaultWriter")}} with {{domxref("WritableStream.getWriter()", "getWriter()")}}, calling {{domxref("WritableStreamDefaultWriter.close()", "close()")}} on it. ## Syntax ```js-nolint close() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} which fulfills with the `undefined` when all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. ### Exceptions - {{jsxref("TypeError")}} - : The stream you are trying to close is locked. ## Examples The following example illustrates several features of the `WritableStream`. It shows the creation of the `WritableStream` with a custom sink and an API-supplied queuing strategy. It then calls a function called `sendMessage()`, passing the newly created stream and a string. Inside this function it calls the stream's `getWriter()` method, which returns an instance of {{domxref("WritableStreamDefaultWriter")}}. A `forEach()` call is used to write each chunk of the string to the stream. Finally, `write()` and `close()` return promises that are processed to deal with success or failure of chunks and streams. Note that in order to be able to call `close()` on the stream itself, the writer must be disconnected using `defaultWriter.releaseLock();`. ```html hidden <ul id="log"></ul> ``` ```js hidden const list = document.getElementById("log"); function log(message) { const listItem = document.createElement("li"); listItem.textContent = message; list.appendChild(listItem); } ``` ```js function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message, { stream: true }); encoded.forEach((chunk) => { defaultWriter.ready .then(() => { defaultWriter.write(chunk); }) .catch((err) => { log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. defaultWriter.ready .then(() => { defaultWriter.releaseLock(); writableStream.close(); }) .then(() => { log("All chunks written / stream closed."); }) .catch((err) => { log("Stream error:", err); }); } const decoder = new TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream( { // Implement the sink write(chunk) { return new Promise((resolve, reject) => { const buffer = new ArrayBuffer(1); const view = new Uint8Array(buffer); view[0] = chunk; const decoded = decoder.decode(view, { stream: true }); const listItem = document.createElement("li"); result += decoded; resolve(); }); }, close() { const listItem = document.createElement("li"); log(`[MESSAGE RECEIVED] ${result}`); }, abort(err) { log("Sink error:", err); }, }, queuingStrategy, ); log("Sending 'Hello, world.' message."); sendMessage("Hello, world.", writableStream); ``` {{EmbedLiveSample("Examples", "100%", "100px")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/writablestream
data/mdn-content/files/en-us/web/api/writablestream/writablestream/index.md
--- title: "WritableStream: WritableStream() constructor" short-title: WritableStream() slug: Web/API/WritableStream/WritableStream page-type: web-api-constructor browser-compat: api.WritableStream.WritableStream --- {{APIRef("Streams")}} The **`WritableStream()`** constructor creates a new {{domxref("WritableStream")}} object instance. ## Syntax ```js-nolint new WritableStream(underlyingSink) new WritableStream(underlyingSink, queuingStrategy) ``` ### Parameters - `underlyingSink` {{optional_inline}} - : An object containing methods and properties that define how the constructed stream instance will behave. The `controller` parameter passed to this object's methods is a {{domxref("WritableStreamDefaultController")}} that provides abort and error signaling. `underlyingSink` can contain the following: - `start(controller)` {{optional_inline}} - : This is a method, called immediately when the object is constructed. The contents of this method are defined by the developer, and should aim to get access to the underlying sink. If this process is to be done asynchronously, it can return a promise to signal success or failure. - `write(chunk, controller)` {{optional_inline}} - : This method, also defined by the developer, will be called when a new chunk of data (specified in the `chunk` parameter) is ready to be written to the underlying sink. It can return a promise to signal success or failure of the write operation. This method will be called only after previous writes have succeeded, and never after the stream is closed or aborted (see below). - `close(controller)` {{optional_inline}} - : This method, also defined by the developer, will be called if the app signals that it has finished writing chunks to the stream. The contents should do whatever is necessary to finalize writes to the underlying sink, and release access to it. If this process is asynchronous, it can return a promise to signal success or failure. This method will be called only after all queued-up writes have succeeded. - `abort(reason)` {{optional_inline}} - : This method, also defined by the developer, will be called if the app signals that it wishes to abruptly close the stream and put it in an errored state. It can clean up any held resources, much like `close()`, but `abort()` will be called even if writes are queued up β€” those chunks will be thrown away. If this process is asynchronous, it can return a promise to signal success or failure. The `reason` parameter contains a string describing why the stream was aborted. - `queuingStrategy` {{optional_inline}} - : An object that optionally defines a queuing strategy for the stream. This takes two parameters: - `highWaterMark` - : A non-negative integer β€” this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. - `size(chunk)` - : A method containing a parameter `chunk` β€” this indicates the size to use for each chunk, in bytes. > **Note:** You could define your own custom > `queuingStrategy`, or use an instance of > {{domxref("ByteLengthQueuingStrategy")}} or {{domxref("CountQueuingStrategy")}} > for this object value. If no `queuingStrategy` is supplied, the default > used is the same as a `CountQueuingStrategy` with a high water mark of 1\. ### Return value An instance of the {{domxref("WritableStream")}} object. ## Examples The following example illustrates several features of this interface. It shows the creation of the `WritableStream` with a custom sink and an API-supplied queuing strategy. It then calls a function called `sendMessage()`, passing the newly created stream and a string. Inside this function it calls the stream's `getWriter()` method, which returns an instance of {{domxref("WritableStreamDefaultWriter")}}. A `forEach()` call is used to write each chunk of the string to the stream. Finally, `write()` and `close()` return promises that are processed to deal with success or failure of chunks and streams. ```js const list = document.querySelector("ul"); function sendMessage(message, writableStream) { // defaultWriter is of type WritableStreamDefaultWriter const defaultWriter = writableStream.getWriter(); const encoder = new TextEncoder(); const encoded = encoder.encode(message, { stream: true }); encoded.forEach((chunk) => { defaultWriter.ready .then(() => defaultWriter.write(chunk)) .then(() => { console.log("Chunk written to sink."); }) .catch((err) => { console.log("Chunk error:", err); }); }); // Call ready again to ensure that all chunks are written // before closing the writer. defaultWriter.ready .then(() => { defaultWriter.close(); }) .then(() => { console.log("All chunks written"); }) .catch((err) => { console.log("Stream error:", err); }); } const decoder = new TextDecoder("utf-8"); const queuingStrategy = new CountQueuingStrategy({ highWaterMark: 1 }); let result = ""; const writableStream = new WritableStream( { // Implement the sink write(chunk) { return new Promise((resolve, reject) => { const buffer = new ArrayBuffer(1); const view = new Uint8Array(buffer); view[0] = chunk; const decoded = decoder.decode(view, { stream: true }); const listItem = document.createElement("li"); listItem.textContent = `Chunk decoded: ${decoded}`; list.appendChild(listItem); result += decoded; resolve(); }); }, close() { const listItem = document.createElement("li"); listItem.textContent = `[MESSAGE RECEIVED] ${result}`; list.appendChild(listItem); }, abort(err) { console.log("Sink error:", err); }, }, queuingStrategy, ); sendMessage("Hello, world.", writableStream); ``` You can find the full code in our [Simple writer example](https://mdn.github.io/dom-examples/streams/simple-writer/). ### Backpressure Because of how backpressure is supported in the API, its implementation in code may be less than obvious. To see how backpressure is implemented look for three things. - The `highWaterMark` property, which is set when creating the counting strategy (line 35), sets the maximum amount of data that the `WritableStream` instance will handle in a single `write()` operation. In this example, it's the maximum amount of data that can be sent to `defaultWriter.write()` (line 11). - The `defaultWriter.ready` property returns a promise that resolves when the sink (the first property of the `WritableStream` constructor) is done writing data. The data source can either write more data (line 11) or call `close()` (line 24). Calling `close()` too early can prevent data from being written. This is why the example calls `defaultWriter.ready` twice (lines 9 and 22). - The {{jsxref("Promise")}} returned by the sink's `write()` method (line 40\) tells the `WritableStream` and its writer when to resolve `defaultWriter.ready`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/rsahashedimportparams/index.md
--- title: RsaHashedImportParams slug: Web/API/RsaHashedImportParams page-type: web-api-interface spec-urls: https://w3c.github.io/webcrypto/#dfn-RsaHashedImportParams --- {{ APIRef("Web Crypto API") }} The **`RsaHashedImportParams`** dictionary of the [Web Crypto API](/en-US/docs/Web/API/Web_Crypto_API) represents the object that should be passed as the `algorithm` parameter into {{domxref("SubtleCrypto.importKey()")}} or {{domxref("SubtleCrypto.unwrapKey()")}}, when importing any RSA-based key pair: that is, when the algorithm is identified as any of [RSASSA-PKCS1-v1_5](/en-US/docs/Web/API/SubtleCrypto/sign#rsassa-pkcs1-v1_5), [RSA-PSS](/en-US/docs/Web/API/SubtleCrypto/sign#rsa-pss), or [RSA-OAEP](/en-US/docs/Web/API/SubtleCrypto/encrypt#rsa-oaep). ## Instance properties - `name` - : A string. This should be set to `RSASSA-PKCS1-v1_5`, `RSA-PSS`, or `RSA-OAEP`, depending on the algorithm you want to use. - `hash` - : A string representing the name of the [digest function](/en-US/docs/Web/API/SubtleCrypto#supported_algorithms) to use. This can be one of `SHA-256`, `SHA-384`, or `SHA-512`. > **Warning:** Although you can technically pass `SHA-1` here, this is strongly discouraged as it is considered vulnerable. ## Examples See the examples for {{domxref("SubtleCrypto.importKey()")}}. ## Specifications {{Specifications}} ## Browser compatibility Browsers that support any RSA-based algorithm for the {{domxref("SubtleCrypto.importKey()")}} or {{domxref("SubtleCrypto.unwrapKey()")}} methods will support this type. ## See also - {{domxref("SubtleCrypto.importKey()")}}. - {{domxref("SubtleCrypto.unwrapKey()")}}.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/xrspace/index.md
--- title: XRSpace slug: Web/API/XRSpace page-type: web-api-interface browser-compat: api.XRSpace --- {{SecureContext_Header}}{{APIRef("WebXR Device API")}} The **`XRSpace`** interface of the [WebXR Device API](/en-US/docs/Web/API/WebXR_Device_API) is an abstract interface providing a common basis for every class which represents a virtual coordinate system within the virtual world, in which its origin corresponds to a physical location. Spatial data in WebXR is always expressed relative to an object based upon one of the descendant interfaces of `XRSpace`, at the time at which a given {{domxref("XRFrame")}} takes place. Numeric values such as pose positions are thus coordinates in the corresponding `XRSpace`, relative to that space's origin. > **Note:** The `XRSpace` interface is never used directly; instead, all spaces are created using one of the interfaces based on `XRSpace`. At this time, those are {{domxref("XRReferenceSpace")}}, {{domxref("XRBoundedReferenceSpace")}}, and {{domxref("XRJointSpace")}}. {{InheritanceDiagram}} ## Interfaces based on XRSpace Below is a list of interfaces based on the `XRSpace` interface. - {{domxref("XRBoundedReferenceSpace")}} - : Represents a reference space which may move within a region of space whose borders are defined by an array of points laid out in clockwise order along the floor to define the passable region of the space. The origin of an `XRBoundedReferenceSpace` is always at floor level, with its X and Z coordinates typically defaulting to a location near the room's center. - {{domxref("XRReferenceSpace")}} - : Represents a reference space which is typically expected to remain static for the duration of the {{domxref("XRSession")}}. While objects may move within the space, the space itself remains fixed in place. There are exceptions to this static nature; most commonly, an `XRReferenceSpace` may move in order to adjust based on reconfiguration of the user's headset or other motion-sensitive device. - {{domxref("XRJointSpace")}} - : Represents the space of an {{domxref("XRHand")}} joint. ## Instance properties _The `XRSpace` interface defines no properties of its own; however, it does inherit the properties of its parent interface, {{domxref("EventTarget")}}._ ## Instance methods _The `XRSpace` interface provides no methods of its own. However, it inherits the methods of {{domxref("EventTarget")}}, its parent interface._ ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/urlsearchparams/index.md
--- title: URLSearchParams slug: Web/API/URLSearchParams page-type: web-api-interface browser-compat: api.URLSearchParams --- {{ApiRef("URL API")}} The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. An object implementing `URLSearchParams` can directly be used in a {{jsxref("Statements/for...of", "for...of")}} structure to iterate over key/value pairs in the same order as they appear in the query string, for example the following two lines are equivalent: ```js for (const [key, value] of mySearchParams) { } for (const [key, value] of mySearchParams.entries()) { } ``` {{AvailableInWorkers}} ## Constructor - {{domxref("URLSearchParams.URLSearchParams", 'URLSearchParams()')}} - : Returns a `URLSearchParams` object instance. ## Instance properties - {{domxref("URLSearchParams.size", 'size')}} {{ReadOnlyInline}} - : Indicates the total number of search parameter entries. ## Instance methods - `URLSearchParams.[@@iterator]()` - : Returns an {{jsxref("Iteration_protocols","iterator")}} allowing iteration through all key/value pairs contained in this object in the same order as they appear in the query string. - {{domxref("URLSearchParams.append()")}} - : Appends a specified key/value pair as a new search parameter. - {{domxref("URLSearchParams.delete()")}} - : Deletes search parameters that match a name, and optional value, from the list of all search parameters. - {{domxref("URLSearchParams.entries()")}} - : Returns an {{jsxref("Iteration_protocols","iterator")}} allowing iteration through all key/value pairs contained in this object in the same order as they appear in the query string. - {{domxref("URLSearchParams.forEach()")}} - : Allows iteration through all values contained in this object via a callback function. - {{domxref("URLSearchParams.get()")}} - : Returns the first value associated with the given search parameter. - {{domxref("URLSearchParams.getAll()")}} - : Returns all the values associated with a given search parameter. - {{domxref("URLSearchParams.has()")}} - : Returns a boolean value indicating if a given parameter, or parameter and value pair, exists. - {{domxref("URLSearchParams.keys()")}} - : Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing iteration through all keys of the key/value pairs contained in this object. - {{domxref("URLSearchParams.set()")}} - : Sets the value associated with a given search parameter to the given value. If there are several values, the others are deleted. - {{domxref("URLSearchParams.sort()")}} - : Sorts all key/value pairs, if any, by their keys. - {{domxref("URLSearchParams.toString()")}} - : Returns a string containing a query string suitable for use in a URL. - {{domxref("URLSearchParams.values()")}} - : Returns an {{jsxref("Iteration_protocols", "iterator")}} allowing iteration through all values of the key/value pairs contained in this object. ## Examples ```js const paramsString = "q=URLUtils.searchParams&topic=api"; const searchParams = new URLSearchParams(paramsString); // Iterating the search parameters for (const p of searchParams) { console.log(p); } console.log(searchParams.has("topic")); // true console.log(searchParams.has("topic", "fish")); // false console.log(searchParams.get("topic") === "api"); // true console.log(searchParams.getAll("topic")); // ["api"] console.log(searchParams.get("foo") === null); // true console.log(searchParams.append("topic", "webdev")); console.log(searchParams.toString()); // "q=URLUtils.searchParams&topic=api&topic=webdev" console.log(searchParams.set("topic", "More webdev")); console.log(searchParams.toString()); // "q=URLUtils.searchParams&topic=More+webdev" console.log(searchParams.delete("topic")); console.log(searchParams.toString()); // "q=URLUtils.searchParams" ``` ```js // Search parameters can also be an object const paramsObj = { foo: "bar", baz: "bar" }; const searchParams = new URLSearchParams(paramsObj); console.log(searchParams.toString()); // "foo=bar&baz=bar" console.log(searchParams.has("foo")); // true console.log(searchParams.get("foo")); // "bar" ``` ### Duplicate search parameters ```js const paramStr = "foo=bar&foo=baz"; const searchParams = new URLSearchParams(paramStr); console.log(searchParams.toString()); // "foo=bar&foo=baz" console.log(searchParams.has("foo")); // true console.log(searchParams.get("foo")); // bar, only returns the first value console.log(searchParams.getAll("foo")); // ["bar", "baz"] ``` ### No URL parsing The `URLSearchParams` constructor does _not_ parse full URLs. However, it will strip an initial leading `?` off of a string, if present. ```js const paramsString1 = "http://example.com/search?query=%40"; const searchParams1 = new URLSearchParams(paramsString1); console.log(searchParams1.has("query")); // false console.log(searchParams1.has("http://example.com/search?query")); // true console.log(searchParams1.get("query")); // null console.log(searchParams1.get("http://example.com/search?query")); // "@" (equivalent to decodeURIComponent('%40')) const paramsString2 = "?query=value"; const searchParams2 = new URLSearchParams(paramsString2); console.log(searchParams2.has("query")); // true const url = new URL("http://example.com/search?query=%40"); const searchParams3 = new URLSearchParams(url.search); console.log(searchParams3.has("query")); // true ``` ### Preserving plus signs The `URLSearchParams` constructor interprets plus signs (`+`) as spaces, which might cause problems. In the example below, we use [hexadecimal escape sequences](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#hexadecimal_escape_sequences) to mimic a string containing binary data (where every byte carries information) that needs to be stored in the URL search params. Note how the encoded string produced by `btoa()` contains `+` and isn't preserved by `URLSearchParams`. ```js const rawData = "\x13Γ \x17@\x1F\x80"; const base64Data = btoa(rawData); // 'E+AXQB+A' const searchParams = new URLSearchParams(`bin=${base64Data}`); // 'bin=E+AXQB+A' const binQuery = searchParams.get("bin"); // 'E AXQB A', '+' is replaced by spaces console.log(atob(binQuery) === rawData); // false ``` You can avoid this by encoding the data with the {{jsxref("encodeURIComponent", "encodeURIComponent()")}}. ```js const rawData = "\x13Γ \x17@\x1F\x80"; const base64Data = btoa(rawData); // 'E+AXQB+A' const encodedBase64Data = encodeURIComponent(base64Data); // 'E%2BAXQB%2BA' const searchParams = new URLSearchParams(`bin=${encodedBase64Data}`); // 'bin=E%2BAXQB%2BA' const binQuery = searchParams.get("bin"); // 'E+AXQB+A' console.log(atob(binQuery) === rawData); // true ``` ### Empty value vs. no value `URLSearchParams` doesn't distinguish between a parameter with nothing after the `=`, and a parameter that doesn't have a `=` altogether. ```js const emptyVal = new URLSearchParams("foo=&bar=baz"); console.log(emptyVal.get("foo")); // returns '' const noEquals = new URLSearchParams("foo&bar=baz"); console.log(noEquals.get("foo")); // also returns '' console.log(noEquals.toString()); // 'foo=&bar=baz' ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `URLSearchParams` in `core-js`](https://github.com/zloirock/core-js#url-and-urlsearchparams) - The {{domxref("URL")}} interface. - [Google Developers: Easy URL manipulation with URLSearchParams](https://developer.chrome.com/blog/urlsearchparams/)
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/tostring/index.md
--- title: "URLSearchParams: toString() method" short-title: toString() slug: Web/API/URLSearchParams/toString page-type: web-api-instance-method browser-compat: api.URLSearchParams.toString --- {{ApiRef("URL API")}} The **`toString()`** method of the {{domxref("URLSearchParams")}} interface returns a query string suitable for use in a URL. > **Note:** This method returns the query string without the question mark. This is different from [`Location.search`](/en-US/docs/Web/API/Location/search), [`HTMLAnchorElement.search`](/en-US/docs/Web/API/HTMLAnchorElement/search), and [`URL.search`](/en-US/docs/Web/API/URL/search), which all include the question mark. {{AvailableInWorkers}} ## Syntax ```js-nolint toString() ``` ### Parameters None. ### Return value A string, without the question mark. (Returns an empty string if no search parameters have been set.) ## Examples ```js const url = new URL("https://example.com?foo=1&bar=2"); const params = new URLSearchParams(url.search); // Add a second foo parameter. params.append("foo", 4); console.log(params.toString()); // Prints 'foo=1&bar=2&foo=4' ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("URL")}} interface. - [Google Developers: Easy URL manipulation with URLSearchParams](https://developer.chrome.com/blog/urlsearchparams/)
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/get/index.md
--- title: "URLSearchParams: get() method" short-title: get() slug: Web/API/URLSearchParams/get page-type: web-api-instance-method browser-compat: api.URLSearchParams.get --- {{ApiRef("URL API")}} The **`get()`** method of the {{domxref("URLSearchParams")}} interface returns the first value associated to the given search parameter. {{AvailableInWorkers}} ## Syntax ```js-nolint get(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value A string if the given search parameter is found; otherwise, **`null`**. ## Examples If the URL of your page is `https://example.com/?name=Jonathan&age=18` you could parse out the 'name' and 'age' parameters using: ```js let params = new URLSearchParams(document.location.search); let name = params.get("name"); // is the string "Jonathan" let age = parseInt(params.get("age"), 10); // is the number 18 ``` Requesting a parameter that isn't present in the query string will return **`null`**: ```js let address = params.get("address"); // null ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/has/index.md
--- title: "URLSearchParams: has() method" short-title: has() slug: Web/API/URLSearchParams/has page-type: web-api-instance-method browser-compat: api.URLSearchParams.has --- {{ApiRef("URL API")}} The **`has()`** method of the {{domxref("URLSearchParams")}} interface returns a boolean value that indicates whether the specified parameter is in the search parameters. A parameter name and optional value are used to match parameters. If only a parameter name is specified, then the method will return `true` if any parameters in the query string match the name, and `false` otherwise. If both a parameter name and value are specified, then the method will return `true` if a parameter matches both the name and value. {{AvailableInWorkers}} ## Syntax ```js-nolint has(name) has(name, value) ``` ### Parameters - `name` - : The name of the parameter to match. - `value` - : The value of the parameter, along with the given name, to match. ### Return value A boolean value. ## Examples ### Check for parameter with specified name This example shows how to check if the query string has any parameters with a particular name. ```html hidden <pre id="log"></pre> ``` ```js hidden const logElement = document.getElementById("log"); function log(text) { logElement.innerText += `${text}\n`; } ``` ```js const url = new URL("https://example.com?foo=1&bar=2&foo=3"); const params = new URLSearchParams(url.search); // has() returns true if the parameter is in the query string log(`bar?:\t${params.has("bar")}`); log(`bark?:\t${params.has("bark")}`); log(`foo?:\t${params.has("foo")}`); ``` The log below shows whether the parameters `bar`, `bark`, and `foo`, are present in the query string. {{EmbedLiveSample('Check for parameter with specified name', '100%', '80')}} ### Check for parameter with specified name and value This example shows how to check whether the query string has a parameter that matches both a particular name and value. ```html hidden <pre id="log"></pre> ``` ```js hidden const logElement = document.getElementById("log"); function log(text) { logElement.innerText += `${text}\n`; } ``` ```js const url = new URL("https://example.com?foo=1&bar=2&foo=3"); const params = new URLSearchParams(url.search); // has() returns true if a parameter with the matching name and value is in the query string log(`bar=1?:\t${params.has("bar", "1")}`); log(`bar=2?:\t${params.has("bar", "2")}`); log(`foo=4?:\t${params.has("foo", "4")}`); ``` Only the second value above should be `true`, as only the parameter name `bar` with value `2` is matched. {{EmbedLiveSample('Check for parameter with specified name and value', '100%', '80')}} If your browser does not support the `value` option the method will match on the name, and all the results should be `true`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `URLSearchParams` in `core-js`](https://github.com/zloirock/core-js#url-and-urlsearchparams)
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/set/index.md
--- title: "URLSearchParams: set() method" short-title: set() slug: Web/API/URLSearchParams/set page-type: web-api-instance-method browser-compat: api.URLSearchParams.set --- {{ApiRef("URL API")}} The **`set()`** method of the {{domxref("URLSearchParams")}} interface sets the value associated with a given search parameter to the given value. If there were several matching values, this method deletes the others. If the search parameter doesn't exist, this method creates it. {{AvailableInWorkers}} ## Syntax ```js-nolint set(name, value) ``` ### Parameters - `name` - : The name of the parameter to set. - `value` - : The value of the parameter to set. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js let url = new URL("https://example.com?foo=1&bar=2"); let params = new URLSearchParams(url.search); // Add a third parameter. params.set("baz", 3); params.toString(); // "foo=1&bar=2&baz=3" ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/append/index.md
--- title: "URLSearchParams: append() method" short-title: append() slug: Web/API/URLSearchParams/append page-type: web-api-instance-method browser-compat: api.URLSearchParams.append --- {{ApiRef("URL API")}} The **`append()`** method of the {{domxref("URLSearchParams")}} interface appends a specified key/value pair as a new search parameter. As shown in the example below, if the same key is appended multiple times it will appear in the parameter string multiple times for each value. {{AvailableInWorkers}} ## Syntax ```js-nolint append(name, value) ``` ### Parameters - `name` - : The name of the parameter to append. - `value` - : The value of the parameter to append. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js let url = new URL("https://example.com?foo=1&bar=2"); let params = new URLSearchParams(url.search); //Add a second foo parameter. params.append("foo", 4); //Query string is now: 'foo=1&bar=2&foo=4' ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("URL")}} - [Google Developers: Easy URL manipulation with URLSearchParams](https://developer.chrome.com/blog/urlsearchparams/)
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/keys/index.md
--- title: "URLSearchParams: keys() method" short-title: keys() slug: Web/API/URLSearchParams/keys page-type: web-api-instance-method browser-compat: api.URLSearchParams.keys --- {{APIRef("URL API")}} The **`keys()`** method of the {{domxref("URLSearchParams")}} interface returns an {{jsxref("Iteration_protocols",'iterator')}} allowing iteration through all keys contained in this object. The keys are string objects. {{AvailableInWorkers}} ## Syntax ```js-nolint keys() ``` ### Parameters None. ### Return value Returns an {{jsxref("Iteration_protocols","iterator")}}. ## Examples ```js // Create a test URLSearchParams object const searchParams = new URLSearchParams("key1=value1&key2=value2"); // Display the keys for (const key of searchParams.keys()) { console.log(key); } ``` The result is: ```plain key1 key2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("URL")}} interface.
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/size/index.md
--- title: "URLSearchParams: size property" short-title: size slug: Web/API/URLSearchParams/size page-type: web-api-instance-property browser-compat: api.URLSearchParams.size --- {{APIRef("URL API")}} The **`size`** read-only property of the {{domxref("URLSearchParams")}} interface indicates the total number of search parameter entries. {{AvailableInWorkers}} ## Value A number indicating the total number of search parameter entries in the {{domxref("URLSearchParams")}} object. ## Examples ### Getting the amount of search parameter entries You can get the total number of search parameter entries like so: ```js const searchParams = new URLSearchParams("c=4&a=2&b=3&a=1"); searchParams.size; // 4 ``` Note how the `a` parameter is given twice, but `size` returns the number of all given entries (4) and not 3. To get the amount of unique keys, you can use a {{jsxref("Set")}}, for example: ```js [...new Set(searchParams.keys())].length; // 3 ``` ### Checking if search parameters exist The `size` property is useful for checking whether there are any search parameters at all: ```js const url = new URL("https://example.com?foo=1&bar=2"); if (url.searchParams.size) { console.log("URL has search parameters!"); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("URL.searchParams")}} - [Polyfill of `URLSearchParams` in `core-js`](https://github.com/zloirock/core-js#url-and-urlsearchparams)
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/values/index.md
--- title: "URLSearchParams: values() method" short-title: values() slug: Web/API/URLSearchParams/values page-type: web-api-instance-method browser-compat: api.URLSearchParams.values --- {{APIRef("URL API")}} The **`values()`** method of the {{domxref("URLsearchParams")}} interface returns an {{jsxref("Iteration_protocols",'iterator')}} allowing iteration through all values contained in this object. The values are string objects. {{AvailableInWorkers}} ## Syntax ```js-nolint values() ``` ### Parameters None. ### Return value Returns an {{jsxref("Iteration_protocols","iterator")}}. ## Examples The following example passes a URL search string to the `URLSearchParams` constructor, then uses the iterator returned by `values()` to print the values to the console. ```js const searchParams = new URLSearchParams("key1=value1&key2=value2"); for (const value of searchParams.values()) { console.log(value); } ``` The result is: ```plain value1 value2 ``` This example does much the same as above, but first casts the iterator into an array. ```js const searchParams = new URLSearchParams("key1=value1&key2=value2"); console.log(Array.from(searchParams.values())); ``` The result is: ```plain ['value1', 'value2'] ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("URL")}} interface.
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/delete/index.md
--- title: "URLSearchParams: delete() method" short-title: delete() slug: Web/API/URLSearchParams/delete page-type: web-api-instance-method browser-compat: api.URLSearchParams.delete --- {{ApiRef("URL API")}} The **`delete()`** method of the {{domxref("URLSearchParams")}} interface deletes specified parameters and their associated value(s) from the list of all search parameters. A parameter name and optional value are used to match parameters. If only a parameter name is specified, then all search parameters that match the name are deleted, along with their associated values. If both a parameter name and value are specified, then all search parameters that match both the parameter name and value are deleted. {{AvailableInWorkers}} ## Syntax ```js-nolint delete(name) delete(name, value) ``` ### Parameters - `name` - : The name of the parameters to be deleted. - `value` {{optional_inline}} - : The value that parameters must match, along with the given name, to be deleted. ### Return value None ({{jsxref("undefined")}}). ## Examples ### Delete all parameters with specified name This example shows how to delete all query parameters (and values) that have a particular name. ```html hidden <pre id="log"></pre> ``` ```js hidden const logElement = document.getElementById("log"); function log(text) { logElement.innerText += `${text}\n`; } ``` ```js const url = new URL("https://example.com?foo=1&bar=2&foo=3"); const params = new URLSearchParams(url.search); log(`Query string (before):\t ${params}`); params.delete("foo"); log(`Query string (after):\t ${params}`); ``` The log below shows that all parameters that have the name of `foo` are deleted. {{EmbedLiveSample('Delete all parameters with specified name', '100%', '50')}} ### Delete parameters with specified name and value This example shows how to delete query parameters that match a particular name and value. ```html hidden <pre id="log"></pre> ``` ```js hidden const logElement = document.getElementById("log"); function log(text) { logElement.innerText += `${text}\n`; } ``` ```js const url = new URL("https://example.com?foo=1&bar=2&foo=3&foo=1"); const params = new URLSearchParams(url.search); log(`Query string (before):\t ${params}`); params.delete("foo", "1"); log(`Query string (after):\t ${params}`); ``` All parameters that match both the parameter `name` and `value` should be deleted (there is no reason to specify two parameters with the same name and value as shown above). {{EmbedLiveSample('Delete parameters with specified name and value', '100%', '50')}} If your browser supports the `value` option, the "after" string should be `bar=2&foo=3`. Otherwise the result will be the same as in the previous example (`bar=2`). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Polyfill of `URLSearchParams` in `core-js`](https://github.com/zloirock/core-js#url-and-urlsearchparams)
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/getall/index.md
--- title: "URLSearchParams: getAll() method" short-title: getAll() slug: Web/API/URLSearchParams/getAll page-type: web-api-instance-method browser-compat: api.URLSearchParams.getAll --- {{ApiRef("URL API")}} The **`getAll()`** method of the {{domxref("URLSearchParams")}} interface returns all the values associated with a given search parameter as an array. {{AvailableInWorkers}} ## Syntax ```js-nolint getAll(name) ``` ### Parameters - `name` - : The name of the parameter to return. ### Return value An array of strings, which may be empty if no values for the given parameter are found. ## Examples ```js let url = new URL("https://example.com?foo=1&bar=2"); let params = new URLSearchParams(url.search); //Add a second foo parameter. params.append("foo", 4); console.log(params.getAll("foo")); //Prints ["1","4"]. ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/foreach/index.md
--- title: "URLSearchParams: forEach() method" short-title: forEach() slug: Web/API/URLSearchParams/forEach page-type: web-api-instance-method browser-compat: api.URLSearchParams.forEach --- {{APIRef("URL API")}} The **`forEach()`** method of the {{domxref("URLSearchParams")}} interface allows iteration through all values contained in this object via a callback function. {{AvailableInWorkers}} ## Syntax ```js-nolint forEach(callback) forEach(callback, thisArg) ``` ### Parameters - `callback` - : Function to execute on each element, which is passed the following arguments: - `value` - : The value of the current entry being processed in the `URLSearchParams` object. - `key` - : The key of the current entry being processed in the `URLSearchParams` object. - `searchParams` - : The `URLSearchParams` object the `forEach()` was called upon. - `thisArg` {{optional_inline}} - : Value to use as `this` when executing `callback`. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js // Create a test URLSearchParams object const searchParams = new URLSearchParams("key1=value1&key2=value2"); // Log the values searchParams.forEach((value, key) => { console.log(value, key); }); ``` The result is: ```plain value1 key1 value2 key2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("URL")}} interface.
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/sort/index.md
--- title: "URLSearchParams: sort() method" short-title: sort() slug: Web/API/URLSearchParams/sort page-type: web-api-instance-method browser-compat: api.URLSearchParams.sort --- {{APIRef("URL API")}} The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. The sort order is according to unicode code points of the keys. This method uses a stable sorting algorithm (i.e. the relative order between key/value pairs with equal keys will be preserved). {{AvailableInWorkers}} ## Syntax ```js-nolint sort() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js // Create a test URLSearchParams object const searchParams = new URLSearchParams("c=4&a=2&b=3&a=1"); // Sort the key/value pairs searchParams.sort(); // Display the sorted query string console.log(searchParams.toString()); ``` The result is: ```plain a=2&a=1&b=3&c=4 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/urlsearchparams/index.md
--- title: "URLSearchParams: URLSearchParams() constructor" short-title: URLSearchParams() slug: Web/API/URLSearchParams/URLSearchParams page-type: web-api-constructor browser-compat: api.URLSearchParams.URLSearchParams --- {{ApiRef("URL API")}} The **`URLSearchParams()`** constructor creates and returns a new {{domxref("URLSearchParams")}} object. {{AvailableInWorkers}} ## Syntax ```js-nolint new URLSearchParams() new URLSearchParams(options) ``` ### Parameters - `options` {{optional_inline}} - : One of: - A string, which will be parsed from `application/x-www-form-urlencoded` format. A leading `'?'` character is ignored. - A literal sequence of name-value string pairs, or any object β€” such as a {{domxref("FormData")}} object β€” with an [iterator](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators#iterators) that produces a sequence of string pairs. Note that {{domxref("File")}} entries will be serialized as `[object File]` rather than as their filename (as they would in an `application/x-www-form-urlencoded` form). - A record of string keys and string values. Note that nesting is not supported. ### Return value A {{domxref("URLSearchParams")}} object instance. ## Examples The following example shows how to create a {{domxref("URLSearchParams")}} object from various inputs. ```js // Retrieve params via url.search, passed into constructor const url = new URL("https://example.com?foo=1&bar=2"); const params1 = new URLSearchParams(url.search); // Get the URLSearchParams object directly from a URL object const params1a = url.searchParams; // Pass in a string literal const params2 = new URLSearchParams("foo=1&bar=2"); const params2a = new URLSearchParams("?foo=1&bar=2"); // Pass in a sequence of pairs const params3 = new URLSearchParams([ ["foo", "1"], ["bar", "2"], ]); // Pass in a record const params4 = new URLSearchParams({ foo: "1", bar: "2" }); ``` This example shows how to build a new URL with an object of search parameters from an existing URL that has search parameters. ```js const url = new URL("https://example.com/?a=hello&b=world"); console.log(url.href); // https://example.com/?a=hello&b=world console.log(url.origin); // https://example.com const add_params = { c: "a", d: new String(2), e: false.toString(), }; const new_params = new URLSearchParams([ ...Array.from(url.searchParams.entries()), // [["a","hello"],["b","world"]] ...Object.entries(add_params), // [["c","a"],["d","2"],["e","false"]] ]).toString(); console.log(new_params); // a=hello&b=world&c=a&d=2&e=false const new_url = new URL(`${url.origin}${url.pathname}?${new_params}`); console.log(new_url.href); // https://example.com/?a=hello&b=world&c=a&d=2&e=false // Here it is as a function that accepts (URL, Record<string, string>) const addSearchParams = (url, params = {}) => new URL( `${url.origin}${url.pathname}?${new URLSearchParams([ ...Array.from(url.searchParams.entries()), ...Object.entries(params), ])}`, ); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/urlsearchparams
data/mdn-content/files/en-us/web/api/urlsearchparams/entries/index.md
--- title: "URLSearchParams: entries() method" short-title: entries() slug: Web/API/URLSearchParams/entries page-type: web-api-instance-method browser-compat: api.URLSearchParams.entries --- {{APIRef("URL API")}} The **`entries()`** method of the {{domxref("URLSearchParams")}} interface returns an {{jsxref("Iteration_protocols",'iterator')}} allowing iteration through all key/value pairs contained in this object. The iterator returns key/value pairs in the same order as they appear in the query string. The key and value of each pair are string objects. {{AvailableInWorkers}} ## Syntax ```js-nolint entries() ``` ### Parameters None. ### Return value Returns an {{jsxref("Iteration_protocols","iterator")}}. ## Examples ```js // Create a test URLSearchParams object const searchParams = new URLSearchParams("key1=value1&key2=value2"); // Display the key/value pairs for (const [key, value] of searchParams.entries()) { console.log(`${key}, ${value}`); } ``` The result is: ```plain key1, value1 key2, value2 ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - The {{domxref("URL")}} interface.
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/pagetransitionevent/index.md
--- title: PageTransitionEvent slug: Web/API/PageTransitionEvent page-type: web-api-interface browser-compat: api.PageTransitionEvent --- {{APIRef("HTML DOM")}} The **`PageTransitionEvent`** event object is available inside handler functions for the [`pageshow`](/en-US/docs/Web/API/Window/pageshow_event) and [`pagehide`](/en-US/docs/Web/API/Window/pagehide_event) events, fired when a document is being loaded or unloaded. {{InheritanceDiagram}} ## Constructor - {{domxref("PageTransitionEvent.PageTransitionEvent", "PageTransitionEvent()")}} - : Creates a new `PageTransitionEvent` object. ## Instance properties _This interface also inherits properties from its parent, {{domxref("Event")}}._ - {{domxref("PageTransitionEvent.persisted")}} {{ReadOnlyInline}} - : Indicates if the document is loading from a cache. ## Example ### HTML ```html <!doctype html> <html lang="en-US"> <body></body> </html> ``` ### JavaScript ```js window.addEventListener("pageshow", (event) => { if (event.persisted) { alert("The page was cached by the browser"); } else { alert("The page was NOT cached by the browser"); } }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`pageshow`](/en-US/docs/Web/API/Window/pageshow_event) event - [`pagehide`](/en-US/docs/Web/API/Window/pagehide_event) event
0
data/mdn-content/files/en-us/web/api/pagetransitionevent
data/mdn-content/files/en-us/web/api/pagetransitionevent/persisted/index.md
--- title: "PageTransitionEvent: persisted property" short-title: persisted slug: Web/API/PageTransitionEvent/persisted page-type: web-api-instance-property browser-compat: api.PageTransitionEvent.persisted --- {{APIRef("HTML DOM")}} The **`persisted`** read-only property indicates if a webpage is loading from a cache. ## Value A boolean value. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/pagetransitionevent
data/mdn-content/files/en-us/web/api/pagetransitionevent/pagetransitionevent/index.md
--- title: "PageTransitionEvent: PageTransitionEvent() constructor" short-title: PageTransitionEvent() slug: Web/API/PageTransitionEvent/PageTransitionEvent page-type: web-api-constructor browser-compat: api.PageTransitionEvent.PageTransitionEvent --- {{APIRef("HTML DOM")}} The **`PageTransitionEvent()`** constructor creates a new {{domxref("PageTransitionEvent")}} object, that is used by the {{domxref("Window/pageshow_event", "pageshow")}} or {{domxref("Window/pagehide_event", "pagehide")}} events, fired at the {{domxref("window")}} object when a page is loaded or unloaded. > **Note:** A web developer doesn't typically need to call this constructor, as the browser creates these objects itself when firing {{domxref("Window/pageshow_event", "pageshow")}} or {{domxref("Window/pagehide_event", "pagehide")}} events. ## Syntax ```js-nolint new PageTransitionEvent(type, options) ``` ### Parameters - `type` - : A string with the name of the event. It is case-sensitive and browsers set it to `pageshow` or `pagehide`. - `options` {{optional_inline}} - : An object that, _in addition to the properties defined in {{domxref("Event/Event", "Event()")}}_, has the following property: - `persisted` {{optional_inline}} - : A boolean indicating if the document is loading from a cache. ### Return value A new {{domxref("PageTransitionEvent")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`pageshow`](/en-US/docs/Web/API/Window/pageshow_event) event - [`pagehide`](/en-US/docs/Web/API/Window/pagehide_event) event
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/filesystem/index.md
--- title: FileSystem slug: Web/API/FileSystem page-type: web-api-interface browser-compat: api.FileSystem --- {{APIRef("File and Directory Entries API")}} The File and Directory Entries API interface **`FileSystem`** is used to represent a file system. These objects can be obtained from the {{domxref("FileSystemEntry.filesystem", "filesystem")}} property on any file system entry. Some browsers offer additional APIs to create and manage file systems, such as Chrome's {{domxref("Window.requestFileSystem", "requestFileSystem()")}} method. This interface will not grant you access to the users' filesystem. Instead, you will have a "virtual drive" within the browser sandbox if you want to gain access to the users' file system, you need to invoke the user, for example by installing a Chrome extension. The relevant Chrome API can be found [here](https://developer.chrome.com/docs/extensions/reference/fileSystem/). ## Basic concepts There are two ways to get access to a `FileSystem` object: 1. You can directly ask for one representing a sandboxed file system created just for your web app directly by calling `window.requestFileSystem()`. If that call is successful, it executes a callback handler, which receives as a parameter a `FileSystem` object describing the file system. 2. You can get it from a file system entry object, through its {{domxref("FileSystemEntry.filesystem", "filesystem")}} property. ## Instance properties - {{domxref("FileSystem.name")}} {{ReadOnlyInline}} - : A string representing the file system's name. This name is unique among the entire list of exposed file systems. - {{domxref("FileSystem.root")}} {{ReadOnlyInline}} - : A {{domxref("FileSystemDirectoryEntry")}} object which represents the file system's root directory. Through this object, you can gain access to all files and directories in the file system. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API) - [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction) - {{domxref("FileSystemEntry")}}, {{domxref("FileSystemFileEntry")}}, and {{domxref("FileSystemDirectoryEntry")}}
0
data/mdn-content/files/en-us/web/api/filesystem
data/mdn-content/files/en-us/web/api/filesystem/name/index.md
--- title: "FileSystem: name property" short-title: name slug: Web/API/FileSystem/name page-type: web-api-instance-property browser-compat: api.FileSystem.name --- {{APIRef("File and Directory Entries API")}} The read-only **`name`** property of the {{domxref("FileSystem")}} interface indicates the file system's name. This string is unique among all file systems currently exposed by the [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API). ## Value A string representing the file system's name. ## Examples ```js // tbd ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API) - [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction) - {{domxref("FileSystem")}}
0
data/mdn-content/files/en-us/web/api/filesystem
data/mdn-content/files/en-us/web/api/filesystem/root/index.md
--- title: "FileSystem: root property" short-title: root slug: Web/API/FileSystem/root page-type: web-api-instance-property browser-compat: api.FileSystem.root --- {{APIRef("File and Directory Entries API")}} The read-only **`root`** property of the {{domxref("FileSystem")}} interface specifies a {{domxref("FileSystemDirectoryEntry")}} object representing the root directory of the file system, for use with the [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API). ## Value A {{domxref("FileSystemDirectoryEntry")}} representing the file system's root directory. ## Examples ```js // tbd ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API) - [Introduction to the File and Directory Entries API](/en-US/docs/Web/API/File_and_Directory_Entries_API/Introduction) - {{domxref("FileSystem")}}
0
data/mdn-content/files/en-us/web/api
data/mdn-content/files/en-us/web/api/devicemotioneventacceleration/index.md
--- title: DeviceMotionEventAcceleration slug: Web/API/DeviceMotionEventAcceleration page-type: web-api-interface browser-compat: api.DeviceMotionEventAcceleration --- {{APIRef("Device Orientation Events")}}{{securecontext_header}} The **`DeviceMotionEventAcceleration`** interface of the {{domxref("Device Orientation Events", "", "", "nocode")}} provides information about the amount of acceleration the device is experiencing along all three axes. ## Instance properties - {{domxref("DeviceMotionEventAcceleration.x")}} {{ReadOnlyInline}} - : The amount of acceleration along the X axis. - {{domxref("DeviceMotionEventAcceleration.y")}} {{ReadOnlyInline}} - : The amount of acceleration along the Y axis. - {{domxref("DeviceMotionEventAcceleration.z")}} {{ReadOnlyInline}} - : The amount of acceleration along the Z axis. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0