Element - Web APIs

Element
=======

**`Element`** is the most general base class from which all element objects (i.e. objects that represent elements) in a `Document` inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from `Element`.

For example, the `HTMLElement` interface is the base interface for HTML elements. Similarly, the `SVGElement` interface is the basis for all SVG elements, and the `MathMLElement` interface is the base interface for MathML elements. Most functionality is specified further down the class hierarchy.

Languages outside the realm of the Web platform, like XUL through the `XULElement` interface, also implement `Element`.

EventTarget

Node

ElementInstance properties
-------------------

*`Element` inherits properties from its parent interface, `Node`, and by extension that interface's parent, `EventTarget`.*

`Element.assignedSlot` Read only

Returns a `HTMLSlotElement` representing the `<slot>` the node is inserted in.

`Element.attributes` Read only

Returns a `NamedNodeMap` object containing the assigned attributes of the corresponding HTML element.

`Element.childElementCount` Read only

Returns the number of child elements of this element.

`Element.children` Read only

Returns the child elements of this element.

`Element.classList` Read only

Returns a `DOMTokenList` containing the list of class attributes.

`Element.className`

A string representing the class of the element.

`Element.clientHeight` Read only

Returns a number representing the inner height of the element.

`Element.clientLeft` Read only

Returns a number representing the width of the left border of the element.

`Element.clientTop` Read only

Returns a number representing the width of the top border of the element.

`Element.clientWidth` Read only

Returns a number representing the inner width of the element.

`Element.elementTiming`
Experimental

A string reflecting the `elementtiming` attribute which marks an element for observation in the `PerformanceElementTiming` API.

`Element.firstElementChild` Read only

Returns the first child element of this element.

`Element.id`

A string representing the id of the element.

`Element.innerHTML`

A string representing the markup of the element's content.

`Element.lastElementChild` Read only

Returns the last child element of this element.

`Element.localName` Read only

A string representing the local part of the qualified name of the element.

`Element.namespaceURI` Read only

The namespace URI of the element, or `null` if it is no namespace.

**Note:** In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the `http://www.w3.org/1999/xhtml` namespace in both HTML and XML trees.

`Element.nextElementSibling` Read only

An `Element`, the element immediately following the given one in the tree, or `null` if there's no sibling node.

`Element.outerHTML`

A string representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.

`Element.part`

Represents the part identifier(s) of the element (i.e. set using the `part` attribute), returned as a `DOMTokenList`.

`Element.prefix` Read only

A string representing the namespace prefix of the element, or `null` if no prefix is specified.

`Element.previousElementSibling` Read only

An `Element`, the element immediately preceding the given one in the tree, or `null` if there is no sibling element.

`Element.scrollHeight` Read only

Returns a number representing the scroll view height of an element.

`Element.scrollLeft`

A number representing the left scroll offset of the element.

`Element.scrollLeftMax`
Non-standard
 Read only

Returns a number representing the maximum left scroll offset possible for the element.

`Element.scrollTop`

A number representing number of pixels the top of the element is scrolled vertically.

`Element.scrollTopMax`
Non-standard
 Read only

Returns a number representing the maximum top scroll offset possible for the element.

`Element.scrollWidth` Read only

Returns a number representing the scroll view width of the element.

`Element.shadowRoot` Read only

Returns the open shadow root that is hosted by the element, or null if no open shadow root is present.

`Element.slot`

Returns the name of the shadow DOM slot the element is inserted in.

`Element.tagName` Read only

Returns a string with the name of the tag for the given element.

### Instance properties included from ARIA

*The `Element` interface also includes the following properties.*

`Element.ariaAtomic`

A string reflecting the `aria-atomic` attribute, which indicates whether assistive technologies will present all, or only parts of, the changed region based on the change notifications defined by the `aria-relevant` attribute.

`Element.ariaAutoComplete`

A string reflecting the `aria-autocomplete` attribute, which indicates whether inputting text could trigger display of one or more predictions of the user's intended value for a combobox, searchbox, or textbox and specifies how predictions would be presented if they were made.

`Element.ariaBusy`

A string reflecting the `aria-busy` attribute, which indicates whether an element is being modified, as assistive technologies may want to wait until the modifications are complete before exposing them to the user.

`Element.ariaChecked`

A string reflecting the `aria-checked` attribute, which indicates the current "checked" state of checkboxes, radio buttons, and other widgets that have a checked state.

`Element.ariaColCount`

A string reflecting the `aria-colcount` attribute, which defines the number of columns in a table, grid, or treegrid.

`Element.ariaColIndex`

A string reflecting the `aria-colindex` attribute, which defines an element's column index or position with respect to the total number of columns within a table, grid, or treegrid.

`Element.ariaColIndexText`
Experimental

A string reflecting the `aria-colindextext` attribute, which defines a human readable text alternative of aria-colindex.

`Element.ariaColSpan`

A string reflecting the `aria-colspan` attribute, which defines the number of columns spanned by a cell or gridcell within a table, grid, or treegrid.

`Element.ariaCurrent`

A string reflecting the `aria-current` attribute, which indicates the element that represents the current item within a container or set of related elements.

`Element.ariaDescription`

A string reflecting the `aria-description` attribute, which defines a string value that describes or annotates the current element.

`Element.ariaDisabled`

A string reflecting the `aria-disabled` attribute, which indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.

`Element.ariaExpanded`

A string reflecting the `aria-expanded` attribute, which indicates whether a grouping element owned or controlled by this element is expanded or collapsed.

`Element.ariaHasPopup`

A string reflecting the `aria-haspopup` attribute, which indicates the availability and type of interactive popup element, such as menu or dialog, that can be triggered by an element.

`Element.ariaHidden`

A string reflecting the `aria-hidden` attribute, which indicates whether the element is exposed to an accessibility API.

`Element.ariaKeyShortcuts`

A string reflecting the `aria-keyshortcuts` attribute, which indicates keyboard shortcuts that an author has implemented to activate or give focus to an element.

`Element.ariaLabel`

A string reflecting the `aria-label` attribute, which defines a string value that labels the current element.

`Element.ariaLevel`

A string reflecting the `aria-level` attribute, which defines the hierarchical level of an element within a structure.

`Element.ariaLive`

A string reflecting the `aria-live` attribute, which indicates that an element will be updated, and describes the types of updates the user agents, assistive technologies, and user can expect from the live region.

`Element.ariaModal`

A string reflecting the `aria-modal` attribute, which indicates whether an element is modal when displayed.

`Element.ariaMultiline`

A string reflecting the `aria-multiline` attribute, which indicates whether a text box accepts multiple lines of input or only a single line.

`Element.ariaMultiSelectable`

A string reflecting the `aria-multiselectable` attribute, which indicates that the user may select more than one item from the current selectable descendants.

`Element.ariaOrientation`

A string reflecting the `aria-orientation` attribute, which indicates whether the element's orientation is horizontal, vertical, or unknown/ambiguous.

`Element.ariaPlaceholder`

A string reflecting the `aria-placeholder` attribute, which defines a short hint intended to aid the user with data entry when the control has no value.

`Element.ariaPosInSet`

A string reflecting the `aria-posinset` attribute, which defines an element's number or position in the current set of listitems or treeitems.

`Element.ariaPressed`

A string reflecting the `aria-pressed` attribute, which indicates the current "pressed" state of toggle buttons.

`Element.ariaReadOnly`

A string reflecting the `aria-readonly` attribute, which indicates that the element is not editable, but is otherwise operable.

`Element.ariaRelevant`
Non-standard

A string reflecting the `aria-relevant` attribute, which indicates what notifications the user agent will trigger when the accessibility tree within a live region is modified. This is used to describe what changes in an `aria-live` region are relevant and should be announced.

`Element.ariaRequired`

A string reflecting the `aria-required` attribute, which indicates that user input is required on the element before a form may be submitted.

`Element.ariaRoleDescription`

A string reflecting the `aria-roledescription` attribute, which defines a human-readable, author-localized description for the role of an element.

`Element.ariaRowCount`

A string reflecting the `aria-rowcount` attribute, which defines the total number of rows in a table, grid, or treegrid.

`Element.ariaRowIndex`

A string reflecting the `aria-rowindex` attribute, which defines an element's row index or position with respect to the total number of rows within a table, grid, or treegrid.

`Element.ariaRowIndexText`
Experimental

A string reflecting the `aria-rowindextext` attribute, which defines a human readable text alternative of aria-rowindex.

`Element.ariaRowSpan`

A string reflecting the `aria-rowspan` attribute, which defines the number of rows spanned by a cell or gridcell within a table, grid, or treegrid.

`Element.ariaSelected`

A string reflecting the `aria-selected` attribute, which indicates the current "selected" state of elements that have a selected state.

`Element.ariaSetSize`

A string reflecting the `aria-setsize` attribute, which defines the number of items in the current set of listitems or treeitems.

`Element.ariaSort`

A string reflecting the `aria-sort` attribute, which indicates if items in a table or grid are sorted in ascending or descending order.

`Element.ariaValueMax`

A string reflecting the `aria-valueMax` attribute, which defines the maximum allowed value for a range widget.

`Element.ariaValueMin`

A string reflecting the `aria-valueMin` attribute, which defines the minimum allowed value for a range widget.

`Element.ariaValueNow`

A string reflecting the `aria-valueNow` attribute, which defines the current value for a range widget.

`Element.ariaValueText`

A string reflecting the `aria-valuetext` attribute, which defines the human-readable text alternative of aria-valuenow for a range widget.

Instance methods
----------------

*`Element` inherits methods from its parents `Node`, and its own parent, `EventTarget`.*

`Element.after()`

Inserts a set of `Node` objects or strings in the children list of the `Element`'s parent, just after the `Element`.

`Element.animate()`

A shortcut method to create and run an animation on an element. Returns the created Animation object instance.

`Element.append()`

Inserts a set of `Node` objects or strings after the last child of the element.

`Element.attachShadow()`

Attaches a shadow DOM tree to the specified element and returns a reference to its `ShadowRoot`.

`Element.before()`

Inserts a set of `Node` objects or strings in the children list of the `Element`'s parent, just before the `Element`.

`Element.checkVisibility()`

Returns whether an element is expected to be visible or not based on configurable checks.

`Element.closest()`

Returns the `Element` which is the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter.

`Element.computedStyleMap()`

Returns a `StylePropertyMapReadOnly` interface which provides a read-only representation of a CSS declaration block that is an alternative to `CSSStyleDeclaration`.

`Element.getAnimations()`

Returns an array of Animation objects currently active on the element.

`Element.getAttribute()`

Retrieves the value of the named attribute from the current node and returns it as a string.

`Element.getAttributeNames()`

Returns an array of attribute names from the current element.

`Element.getAttributeNode()`

Retrieves the node representation of the named attribute from the current node and returns it as an `Attr`.

`Element.getAttributeNodeNS()`

Retrieves the node representation of the attribute with the specified name and namespace, from the current node and returns it as an `Attr`.

`Element.getAttributeNS()`

Retrieves the value of the attribute with the specified namespace and name from the current node and returns it as a string.

`Element.getBoundingClientRect()`

Returns the size of an element and its position relative to the viewport.

`Element.getBoxQuads()`
Experimental

Returns a list of `DOMQuad` objects representing the CSS fragments of the node.

`Element.getClientRects()`

Returns a collection of rectangles that indicate the bounding rectangles for each line of text in a client.

`Element.getElementsByClassName()`

Returns a live `HTMLCollection` that contains all descendants of the current element that possess the list of classes given in the parameter.

`Element.getElementsByTagName()`

Returns a live `HTMLCollection` containing all descendant elements, of a particular tag name, from the current element.

`Element.getElementsByTagNameNS()`

Returns a live `HTMLCollection` containing all descendant elements, of a particular tag name and namespace, from the current element.

`Element.hasAttribute()`

Returns a boolean value indicating if the element has the specified attribute or not.

`Element.hasAttributeNS()`

Returns a boolean value indicating if the element has the specified attribute, in the specified namespace, or not.

`Element.hasAttributes()`

Returns a boolean value indicating if the element has one or more HTML attributes present.

`Element.hasPointerCapture()`

Indicates whether the element on which it is invoked has pointer capture for the pointer identified by the given pointer ID.

`Element.insertAdjacentElement()`

Inserts a given element node at a given position relative to the element it is invoked upon.

`Element.insertAdjacentHTML()`

Parses the text as HTML or XML and inserts the resulting nodes into the tree in the position given.

`Element.insertAdjacentText()`

Inserts a given text node at a given position relative to the element it is invoked upon.

`Element.matches()`

Returns a boolean value indicating whether or not the element would be selected by the specified selector string.

`Element.prepend()`

Inserts a set of `Node` objects or strings before the first child of the element.

`Element.querySelector()`

Returns the first `Node` which matches the specified selector string relative to the element.

`Element.querySelectorAll()`

Returns a `NodeList` of nodes which match the specified selector string relative to the element.

`Element.releasePointerCapture()`

Releases (stops) pointer capture that was previously set for a specific `pointer event`.

`Element.remove()`

Removes the element from the children list of its parent.

`Element.removeAttribute()`

Removes the named attribute from the current node.

`Element.removeAttributeNode()`

Removes the node representation of the named attribute from the current node.

`Element.removeAttributeNS()`

Removes the attribute with the specified name and namespace, from the current node.

`Element.replaceChildren()`

Replaces the existing children of a `Node` with a specified new set of children.

`Element.replaceWith()`

Replaces the element in the children list of its parent with a set of `Node` objects or strings.

`Element.requestFullscreen()`

Asynchronously asks the browser to make the element fullscreen.

`Element.requestPointerLock()`

Allows to asynchronously ask for the pointer to be locked on the given element.

`Element.scroll()`

Scrolls to a particular set of coordinates inside a given element.

`Element.scrollBy()`

Scrolls an element by the given amount.

`Element.scrollIntoView()`

Scrolls the page until the element gets into the view.

`Element.scrollIntoViewIfNeeded()`
Non-standard

Scrolls the current element into the visible area of the browser window if it's not already within the visible area of the browser window. **Use the standard `Element.scrollIntoView()` instead.**

`Element.scrollTo()`

Scrolls to a particular set of coordinates inside a given element.

`Element.setAttribute()`

Sets the value of a named attribute of the current node.

`Element.setAttributeNode()`

Sets the node representation of the named attribute from the current node.

`Element.setAttributeNodeNS()`

Sets the node representation of the attribute with the specified name and namespace, from the current node.

`Element.setAttributeNS()`

Sets the value of the attribute with the specified name and namespace, from the current node.

`Element.setCapture()`
Non-standard

Deprecated

Sets up mouse event capture, redirecting all mouse events to this element.

`Element.setHTML()`
Experimental

Parses and sanitizes a string of HTML and inserts into the DOM as a subtree of the element.

`Element.setPointerCapture()`

Designates a specific element as the capture target of future pointer events.

`Element.toggleAttribute()`

Toggles a boolean attribute, removing it if it is present and adding it if it is not present, on the specified element.

Events
------

Listen to these events using `addEventListener()` or by assigning an event listener to the `oneventname` property of this interface.

`afterscriptexecute`
Non-standard

Fired when a script has been executed.

`beforematch`
Experimental

Fires on an element that is in the *hidden until found* state, when the browser is about to reveal its content because the user has found the content through the "find in page" feature or through fragment navigation.

`beforescriptexecute`
Non-standard

Fired when a script is about to be executed.

`contentvisibilityautostatechange`
Experimental

Fires on any element with `content-visibility: auto` set on it when it starts or stops being relevant to the user and skipping its contents.

`scroll`

Fired when the document view or an element has been scrolled.

`scrollend`

Fires when the document view has completed scrolling.

`securitypolicyviolation`

Fired when a Content Security Policy is violated.

`wheel`

Fired when the user rotates a wheel button on a pointing device (typically a mouse).

### Animation events

`animationcancel`

Fired when an animation unexpectedly aborts.

`animationend`

Fired when an animation has completed normally.

`animationiteration`

Fired when an animation iteration has completed.

`animationstart`

Fired when an animation starts.

### Clipboard events

`copy`

Fired when the user initiates a copy action through the browser's user interface.

`cut`

Fired when the user initiates a cut action through the browser's user interface.

`paste`

Fired when the user initiates a paste action through the browser's user interface.

### Composition events

`compositionend`

Fired when a text composition system such as an input method editor completes or cancels the current composition session.

`compositionstart`

Fired when a text composition system such as an input method editor starts a new composition session.

`compositionupdate`

Fired when a new character is received in the context of a text composition session controlled by a text composition system such as an input method editor.

### Focus events

`blur`

Fired when an element has lost focus.

`focus`

Fired when an element has gained focus.

`focusin`

Fired when an element has gained focus, after `focus`.

`focusout`

Fired when an element has lost focus, after `blur`.

### Fullscreen events

`fullscreenchange`

Sent to an `Element` when it transitions into or out of fullscreen mode.

`fullscreenerror`

Sent to an `Element` if an error occurs while attempting to switch it into or out of fullscreen mode.

### Keyboard events

`keydown`

Fired when a key is pressed.

`keypress`
Deprecated

Fired when a key that produces a character value is pressed down.

`keyup`

Fired when a key is released.

### Mouse events

`auxclick`

Fired when a non-primary pointing device button (e.g., any mouse button other than the left button) has been pressed and released on an element.

`click`

Fired when a pointing device button (e.g., a mouse's primary button) is pressed and released on a single element.

`contextmenu`

Fired when the user attempts to open a context menu.

`dblclick`

Fired when a pointing device button (e.g., a mouse's primary button) is clicked twice on a single element.

`DOMActivate`
Deprecated

Occurs when an element is activated, for instance, through a mouse click or a keypress.

`DOMMouseScroll`
Deprecated

Non-standard

Occurs when mouse wheel or similar device is operated and the accumulated scroll amount is over 1 line or 1 page since last event.

`mousedown`

Fired when a pointing device button is pressed on an element.

`mouseenter`

Fired when a pointing device (usually a mouse) is moved over the element that has the listener attached.

`mouseleave`

Fired when the pointer of a pointing device (usually a mouse) is moved out of an element that has the listener attached to it.

`mousemove`

Fired when a pointing device (usually a mouse) is moved while over an element.

`mouseout`

Fired when a pointing device (usually a mouse) is moved off the element to which the listener is attached or off one of its children.

`mouseover`

Fired when a pointing device is moved onto the element to which the listener is attached or onto one of its children.

`mouseup`

Fired when a pointing device button is released on an element.

`mousewheel`
Deprecated

Non-standard

Fired when a mouse wheel or similar device is operated.

`MozMousePixelScroll`
Deprecated

Non-standard

Fired when a mouse wheel or similar device is operated.

`webkitmouseforcechanged`
Non-standard

Fired each time the amount of pressure changes on the trackpadtouchscreen.

`webkitmouseforcedown`
Non-standard

Fired after the mousedown event as soon as sufficient pressure has been applied to qualify as a "force click".

`webkitmouseforcewillbegin`
Non-standard

Fired before the `mousedown` event.

`webkitmouseforceup`
Non-standard

Fired after the `webkitmouseforcedown` event as soon as the pressure has been reduced sufficiently to end the "force click".

### Pointer events

`gotpointercapture`

Fired when an element captures a pointer using `setPointerCapture()`.

`lostpointercapture`

Fired when a captured pointer is released.

`pointercancel`

Fired when a pointer event is canceled.

`pointerdown`

Fired when a pointer becomes active.

`pointerenter`

Fired when a pointer is moved into the hit test boundaries of an element or one of its descendants.

`pointerleave`

Fired when a pointer is moved out of the hit test boundaries of an element.

`pointermove`

Fired when a pointer changes coordinates.

`pointerout`

Fired when a pointer is moved out of the *hit test* boundaries of an element (among other reasons).

`pointerover`

Fired when a pointer is moved into an element's hit test boundaries.

`pointerrawupdate`
Experimental

Fired when a pointer changes any properties that don't fire `pointerdown` or `pointerup` events.

`pointerup`

Fired when a pointer is no longer active.

### Touch events

`gesturechange`
Non-standard

Fired when digits move during a touch gesture.

`gestureend`
Non-standard

Fired when there are no longer multiple fingers contacting the touch surface, thus ending the gesture.

`gesturestart`
Non-standard

Fired when multiple fingers contact the touch surface, thus starting a new gesture.

`touchcancel`

Fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created).

`touchend`

Fired when one or more touch points are removed from the touch surface.

`touchmove`

Fired when one or more touch points are moved along the touch surface.

`touchstart`

Fired when one or more touch points are placed on the touch surface.

### Transition events

`transitioncancel`

An `Event` fired when a CSS transition has been cancelled.

`transitionend`

An `Event` fired when a CSS transition has finished playing.

`transitionrun`

An `Event` fired when a CSS transition is created (i.e., when it is added to a set of running transitions), though not necessarily started.

`transitionstart`

An `Event` fired when a CSS transition has started transitioning.

Specifications
--------------

| Specification |
| --- |
| DOM Standard # interface-element |
| Pointer Events # extensions-to-the-element-interface |
| Pointer Lock 2.0 # extensions-to-the-element-interface |
| Fullscreen API Standard # api |
| DOM Parsing and Serialization # extensions-to-the-element-interface |
| CSSOM View Module # extension-to-the-element-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Web Workers API - Web APIs

Web Workers API
===============

**Web Workers** makes it possible to run a script operation in a background thread separate from the main execution thread of a web application. The advantage of this is that laborious processing can be performed in a separate thread, allowing the main (usually the UI) thread to run without being blocked/slowed down.

Web Workers concepts and usage
------------------------------

A worker is an object created using a constructor (e.g. `Worker()`) that runs a named JavaScript file — this file contains the code that will run in the worker thread.

In addition to the standard JavaScript set of functions (such as `String`, `Array`, `Object`, `JSON`, etc.), you can run almost any code you like inside a worker thread. There are some exceptions: for example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the `Window` object. For information about the code that you *can* run see worker global context and functions, and supported web APIs below.

Data is sent between workers and the main thread via a system of messages — both sides send their messages using the `postMessage()` method, and respond to messages via the `onmessage` event handler (the message is contained within the `message` event's `data` property). The data is copied rather than shared.

Workers may in turn spawn new workers, as long as those workers are hosted within the same origin as the parent page.

In addition, workers can make network requests using the `fetch()` or `XMLHttpRequest` APIs (although note that the `responseXML` attribute of `XMLHttpRequest` will always be `null`).

### Worker types

There are a number of different types of workers:

* Dedicated workers are workers that are utilized by a single script. This context is represented by a `DedicatedWorkerGlobalScope` object.
* Shared workers are workers that can be utilized by multiple scripts running in different windows, IFrames, etc., as long as they are in the same domain as the worker. They are a little more complex than dedicated workers — scripts must communicate via an active port.
* Service Workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.

**Note:** As per the Web workers Spec, worker error events should not bubble (see Firefox bug 1188141). This has been implemented in Firefox 42.

### Worker global contexts and functions

Workers run in a different global context than the current `window`! While `Window` is not directly available to workers, many of the same methods are defined in a shared mixin (`WindowOrWorkerGlobalScope`), and made available to workers through their own `WorkerGlobalScope`-derived contexts:

* `DedicatedWorkerGlobalScope` for dedicated workers
* `SharedWorkerGlobalScope` for shared workers
* `ServiceWorkerGlobalScope` for service workers

Some of the functions (a subset) that are common to all workers and to the main thread (from `WindowOrWorkerGlobalScope`) are:

* `atob()`
* `btoa()`
* `clearInterval()`
* `clearTimeout()`
* `createImageBitmap()`
* `dump()`
Non-standard
* `fetch()`
* `queueMicrotask()`
* `reportError()`
* `setInterval()`
* `setTimeout()`
* `structuredClone()`
* `requestAnimationFrame()` (dedicated workers only)
* `cancelAnimationFrame()` (dedicated workers only)

The following functions are **only** available to workers:

* `importScripts()`,
* `postMessage()` (dedicated workers only).
### Supported Web APIs

**Note:** If a listed API is supported by a platform in a particular version, then it can generally be assumed to be available in web workers. You can also test support for a particular object/function using the site: https://worker-playground.glitch.me/

The following Web APIs are available to workers:

* Background Fetch API
* Background Synchronization API
* Barcode Detection API
* Broadcast Channel API
* Canvas API
* Channel Messaging API
* Console API
* Compression Streams API
* CSS Font Loading API
* `CustomEvent`
* Encoding API (e.g. `TextEncoder`, `TextDecoder`)
* Fetch API
* File API
* File System API
* Idle Detection API
* IndexedDB API
* Media Capabilities API
* Media Source Extensions API (dedicated workers only)
* Network Information API
* Notifications API
* Payment Handler API
* Performance API
* Permissions API
* Prioritized Task Scheduling API
* Push API
* Server-Sent Events
* Service Worker API
* Streams API
* Trusted Types API
* URL API (e.g. `URL`)
* URL Pattern API
* User-Agent Client Hints API
* WebCodecs API
* Web Crypto API (e.g. `Crypto`)
* Web Locks API
* Web Serial API
* Web Periodic Background Synchronization API
* WebGPU API
* WebUSB API
* WebSockets API
* XMLHttpRequest API

Workers can also spawn other workers, so these APIs are also available:

* `Worker`
* `WorkerGlobalScope`
* `WorkerLocation`
* `WorkerNavigator`
Web Worker interfaces
---------------------

`Worker`

Represents a running worker thread, allowing you to pass messages to the running worker code.

`WorkerLocation`

Defines the absolute location of the script executed by the `Worker`.

`SharedWorker`

Represents a specific kind of worker that can be accessed from several browsing contexts (i.e. windows, tabs, or iframes) or even other workers.

`WorkerGlobalScope`

Represents the generic scope of any worker (doing the same job as `Window` does for normal web content). Different types of worker have scope objects that inherit from this interface and add more specific features.

`DedicatedWorkerGlobalScope`

Represents the scope of a dedicated worker, inheriting from `WorkerGlobalScope` and adding some dedicated features.

`SharedWorkerGlobalScope`

Represents the scope of a shared worker, inheriting from `WorkerGlobalScope` and adding some dedicated features.

`WorkerNavigator`

Represents the identity and state of the user agent (the client).

Examples
--------

We have created a couple of demos to show web worker usage:

* Basic dedicated worker example (run dedicated worker).
* Basic shared worker example (run shared worker).
* OffscreenCanvas worker example (run OffscreenCanvas worker).

You can find out more information on how these demos work in Using Web Workers.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # workers |

See also
--------

* Using Web Workers
* `Worker` interface
* `SharedWorker` interface
* Service Worker API


Sensor - Web APIs

Sensor
======

The **`Sensor`** interface of the Sensor APIs is the base class for all the other sensor interfaces. This interface cannot be used directly. Instead it provides properties, event handlers, and methods accessed by interfaces that inherit from it.

This feature may be blocked by a Permissions Policy set on your server.

EventTarget

Sensor
When initially created, the `Sensor` object is *idle*, meaning it does not take measures. Once the `start()` method is called, it prepares itself to read data and, once ready, the `activate` event is sent and the sensor becomes *activated*. It then sends a `reading` event each time new data is available.

In case of an error, the `error` event is sent, reading stops, and the `Sensor` object becomes *idle* again. The `start()` method needs to be called again before it can read further data.

Interfaces based on `Sensor`
----------------------------

Below is a list of interfaces based on the `Sensor` interface.

* `Accelerometer`
* `AmbientLightSensor`
* `GravitySensor`
* `Gyroscope`
* `LinearAccelerationSensor`
* `Magnetometer`
* `OrientationSensor`
Instance properties
-------------------

`Sensor.activated` Read only

Returns a boolean value indicating whether the sensor is active.

`Sensor.hasReading` Read only

Returns a boolean value indicating whether the sensor has a reading.

`Sensor.timestamp` Read only

Returns the timestamp of the latest sensor reading.

Instance methods
----------------

`Sensor.start()`

Activates one of the sensors based on `Sensor`.

`Sensor.stop()`

Deactivates one of the sensors based on `Sensor`.

Events
------

`activate`

Fired when a sensor becomes activated.

`error`

Fired when an exception occurs on a sensor.

`reading`

Fired when a new reading is available on a sensor.

Specifications
--------------

| Specification |
| --- |
| Generic Sensor API # the-sensor-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


Barcode Detection API - Web APIs

Barcode Detection API
=====================

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Note:** This feature is available in Web Workers

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The Barcode Detection API detects linear and two-dimensional barcodes in images.

Concepts and usage
------------------

Support for barcode recognition within web apps unlocks a variety of use cases through supported barcode formats. QR codes can be used for online payments, web navigation or establishing social media connections, Aztec codes can be used to scan boarding passes and shopping apps can use EAN or UPC barcodes to compare prices of physical items.

 Detection is achieved through the `detect()` method, which takes an image object; it can be one of these objects:
 a `HTMLImageElement`,
 a `SVGImageElement`,
 a `HTMLVideoElement`,
 a `HTMLCanvasElement`,
 an `ImageBitmap`,
 an `OffscreenCanvas`,
 a `VideoFrame`,
 a `Blob`,
 or an `ImageData`.
 Optional parameters can be passed to the `BarcodeDetector` constructor to provide hints on which barcode formats to detect.

### Supported barcode formats

The Barcode Detection API supports the following barcode formats:

| Format | Description | Image |
| --- | --- | --- |
| aztec |
 A square two-dimensional matrix following iso24778 and with a square
 bullseye pattern at their center, thus resembling an Aztec pyramid. Does
 not require a surrounding blank zone.
  | A sample image of an Aztec barcode. A square with smaller black and white squares inside |
| code\_128 |
 A linear (one-dimensional), bidirectionally-decodable, self-checking
 barcode following iso15417 and able to encode all 128 characters of
 ASCII (hence the naming).
  | An image of a code-128 barcode. A horizontal distribution of vertical black and white lines |
| code\_39 |
 A linear (one-dimensional), self-checking barcode following iso16388. It
 is a discrete and variable-length barcode type.
  | An image of a code-39 barcode. A horizontal distribution of vertical black and white lines |
| code\_93 |
 A linear, continuous symbology with a variable length following bc5. It
 offers a larger information density than Code 128 and the visually
 similar Code 39. Code 93 is used primarily by Canada Post to encode
 supplementary delivery information.
  | An image of a code 93 format barcode. A horizontal distribution of white and black horizontal lines |
| codabar | A linear barcode representing characters 0-9, A-D and symbols - . $ / + | An image of a codabar format barcode. A horizontal distribution of black and white vertical lines |
| data\_matrix |
 An orientation-independent two-dimensional barcode composed of black and
 white modules arranged in either a square or rectangular pattern
 following iso16022.
  | An example of a data matrix barcode. A square filled with smaller black and white squares |
| ean\_13 | A linear barcode based on the UPC-A standard and defined in iso15420. | An image of an EAN-13 format barcode. A horizontal distribution of white and black lines |
| ean\_8 | A linear barcode defined in iso15420 and derived from EAN-13. | An image of an EAN-8 format barcode. A horizontal distribution of vertical black and white lines |
| itf |
 A continuous, self-checking, bidirectionally decodable barcode. It will
 always encode 14 digits.
  | An image of an ITF Barcode. A horizontal distribution of white and black lines |
| pdf417 |
 A continuous two-dimensional barcode symbology format with multiple rows
 and columns. It's bi-directionally decodable and uses the iso15438
 standard.
  | An example of a pdf417 barcode format. A rectangle of smaller black and white squares |
| qr\_code |
 A two-dimensional barcode that uses the iso18004 standard. The
 information encoded can be text, URL or other data.
  | An example of a QR code. A square of smaller black and white squares |
| upc\_a |
 One of the most common linear barcode types and is widely applied to
 retail in the United States. Defined in iso15420, it represents digits
 by strips of bars and spaces, each digit being associated to a unique
 pattern of 2 bars and 2 spaces, both of variable width. UPC-A can encode
 12 digits that are uniquely assigned to each trade item, and it's
 technically a subset of EAN-13 (UPC-A codes are represented in EAN-13
 with the first character set to 0).
  | An image of a upc-a barcode. A rectangle of black and white vertical lines with numbers underneath |
| upc\_e |
 A variation of UPC-A defined in iso15420, compressing out unnecessary
 zeros for a more compact barcode.
  | An image of a upc-e barcode. A rectangle of black and white vertical lines |
| unknown |
 This value is used by the platform to signify that it does not know or
 specify which barcode format is being detected or supported.
  |  |

You can check for formats supported by the user agent via the `getSupportedFormats()` method.

Interfaces
----------

`BarcodeDetector`
Experimental

The `BarcodeDetector` interface of the Barcode Detection API allows detection of linear and two dimensional barcodes in images.

Examples
--------

### Creating A Detector

This example tests for browser compatibility and creates a new barcode detector object, with specified supported formats.

```js
// check compatibility
if (!("BarcodeDetector" in globalThis)) {
  console.log("Barcode Detector is not supported by this browser.");
} else {
  console.log("Barcode Detector supported!");

  // create new detector
  const barcodeDetector = new BarcodeDetector({
    formats: ["code\_39", "codabar", "ean\_13"],
  });
}
```

### Getting Supported Formats

The following example calls the `getSupportedFormats()` method and logs the results to the console.

```js
// check supported types
BarcodeDetector.getSupportedFormats().then((supportedFormats) => {
  supportedFormats.forEach((format) => console.log(format));
});
```

### Detect Barcodes

This example uses the `detect()` method to detect the barcodes within the given image. These are iterated over and the barcode data is logged to the console.

```js
barcodeDetector
  .detect(imageEl)
  .then((barcodes) => {
    barcodes.forEach((barcode) => console.log(barcode.rawValue));
  })
  .catch((err) => {
    console.log(err);
  });
```

Specifications
--------------

| Specification |
| --- |
| Accelerated Shape Detection in Images # barcode-detection-api |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* barcodefaq.com: A website with information about different barcodes and examples of the different types.
* The Shape Detection API: a picture is worth a thousand words, faces, and barcodes


SVGPointList - Web APIs

SVGPointList
============

The **`SVGPointList`** interface represents a list of `SVGPoint` objects.

An `SVGPointList` can be designated as read-only, which means that attempts to modify the object will result in an exception being thrown.

Instance properties
-------------------

`SVGPointList.length` Read only

Returns the number of points in the list.

`SVGPointList.numberOfItems` Read only

Returns the number of points in the list.

Instance methods
----------------

`SVGPointList.clear()`

Removes all items in the list.

`SVGPointList.initialize()`

First removes all items in the list, then adds a single value to the list.

`SVGPointList.getItem()`

Gets an item from the list at a specified position.

`SVGPointList.insertItemBefore()`

Inserts an element into the list at a specified position.

`SVGPointList.replaceItem()`

Replaces an item in the list with a new item.

`SVGPointList.removeItem()`

Removes an item from the list.

`SVGPointList.appendItem()`

Adds an item to the end of the list.

Examples
--------

The following example shows an SVG which contains a `<polyline>` with five coordinate pairs. The `points` property returns an `SVGPointList`.

```html
<svg viewBox="-10 -10 120 120" xmlns="http://www.w3.org/2000/svg">
  <polyline
 id="example"
 stroke="black"
 fill="none"
 points="50,0 21,90 98,35 2,35 79,90" />
</svg>
```

```js
let example = document.getElementById("example");
console.log(example.points); //an SVGPointList
```

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # InterfaceSVGPointList |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


HTMLLIElement - Web APIs

HTMLLIElement
=============

The **`HTMLLIElement`** interface exposes specific properties and methods (beyond those defined by regular `HTMLElement` interface it also has available to it by inheritance) for manipulating list elements.

EventTarget

Node

Element

HTMLElement

HTMLLIElementInstance properties
-------------------

*Inherits properties from its parent, `HTMLElement`.*

`HTMLLIElement.type`
Deprecated

A string representing the type of the bullets, `"disc"`, `"square"` or `"circle"`. As the standard way of defining the list type is via the CSS `list-style-type` property, use the CSSOM methods to set it via a script.

`HTMLLIElement.value`

A `long` indicating the ordinal position of the *list element* inside a given `<ol>`. It reflects the `value` attribute of the HTML `<li>` element, and can be smaller than `0`. If the `<li>` element is not a child of an `<ol>` element, the property has no meaning.

Instance methods
----------------

*No specific method; inherits methods from its parent, `HTMLElement`.*

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmllielement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The HTML element implementing this interface: `<li>`


HTMLFrameSetElement - Web APIs

HTMLFrameSetElement
===================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`HTMLFrameSetElement`** interface provides special properties (beyond those of the regular `HTMLElement` interface they also inherit) for manipulating `<frameset>` elements.

EventTarget

Node

Element

HTMLElement

HTMLFrameSetElementInstance properties
-------------------

*Inherits properties from its parent, `HTMLElement`.*

`HTMLFrameSetElement.cols`
Deprecated

A string structured as a comma-separated list specifying the width of each column inside a frameset.

`HTMLFrameSetElement.rows`
Deprecated

A string structured as a comma-separated list specifying the height of each column inside a frameset.

Instance methods
----------------

*No specific method; inherits methods from its parent, `HTMLElement`.*

Event handlers
--------------

The `HTMLElement` events are inherited.

The following `Window` `onXYZ` event handler properties are also available as aliases targeting the `window` object. However, it is advised to listen to them on the `window` object directly rather than on `HTMLFrameSetElement`.

**Note:** Using `addEventListener()` on `HTMLFrameSetElement` will not work for the `onXYZ` event handlers listed below. Listen to the events on the `window` object instead.

`HTMLFrameSetElement.onafterprint`

Fired after the associated document has started printing or the print preview has been closed.

`HTMLFrameSetElement.onbeforeprint`

Fired when the associated document is about to be printed or previewed for printing.

`HTMLFrameSetElement.onbeforeunload`

Fired when the window, the document and its resources are about to be unloaded.

`HTMLFrameSetElement.ongamepadconnected`

Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.

`HTMLFrameSetElement.ongamepaddisconnected`

Fired when the browser detects that a gamepad has been disconnected.

`HTMLFrameSetElement.onhashchange`

Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol).

`HTMLFrameSetElement.onlanguagechange`

Fired when the user's preferred language changes.

`HTMLFrameSetElement.onmessage`

Fired when the window receives a message, for example from a call to `Window.postMessage()` from another browsing context.

`HTMLFrameSetElement.onmessageerror`

Fired when the window receives a message that can't be deserialized.

`HTMLFrameSetElement.onoffline`

Fired when the browser has lost access to the network and the value of `Navigator.onLine` switches to `false`.

`HTMLFrameSetElement.ononline`

Fired when the browser has gained access to the network and the value of `Navigator.onLine` switches to `true`.

`HTMLFrameSetElement.onpagehide`

Fired when the browser hides the current page in the process of presenting a different page from the session's history.

`HTMLFrameSetElement.onpageshow`

Fired when the browser displays the window's document due to navigation.

`HTMLFrameSetElement.onpopstate`

Fired when the active history entry changes while the user navigates the session history.

`HTMLFrameSetElement.onrejectionhandled`

Fired whenever a JavaScript `Promise` is rejected and the rejection has been handled.

`HTMLFrameSetElement.onstorage`

Fired when a storage area (`localStorage`) has been modified in the context of another document.

`HTMLFrameSetElement.onunhandledrejection`

Fired whenever a `Promise` is rejected but the rejection was not handled.

`HTMLFrameSetElement.onunload`

Fired when the document is being unloaded.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # htmlframesetelement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* HTML element implementing this interface: `<frameset>`
* The equivalent of this element outside of frames: `HTMLFrameSetElement`.


WEBGL_debug_shaders extension - Web APIs

WEBGL\_debug\_shaders extension
===============================

The **`WEBGL_debug_shaders`** extension is part of the WebGL API and exposes a method to debug shaders from privileged contexts.

This extension is not directly available to websites as the way of how the shader is translated may uncover personally-identifiable information to the web page about the kind of graphics card in the user's computer.

WebGL extensions are available using the `WebGLRenderingContext.getExtension()` method. For more information, see also Using Extensions in the WebGL tutorial.

**Note:** Depending on the privacy settings of the browser, this extension might only be available to privileged contexts.

This extension is available to both, WebGL1 and WebGL2 contexts.

Instance methods
----------------

`WEBGL_debug_shaders.getTranslatedShaderSource()`

Returns the translated shader source.

Specifications
--------------

| Specification |
| --- |
| WebGL WEBGL\_debug\_shaders Khronos Ratified Extension Specification  |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `WebGLRenderingContext.getExtension()`


NDEFMessage - Web APIs

NDEFMessage
===========

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`NDEFMessage`** interface of the Web NFC API represents the content of an NDEF message that has been read from or could be written to an NFC tag. An instance is acquired by calling the `NDEFMessage()` constructor or from the `NDEFReadingEvent.message` property, which is passed to the `reading` event.

Constructor
-----------

`NDEFMessage()`
Experimental

Creates a new `NDEFMessage` object, initialized with the given NDEF records.

Attributes
----------

`NDEFMessage.records` Read only
Experimental

Returns the list of NDEF records contained in the message.

Specifications
--------------

| Specification |
| --- |
| Web NFC API # dom-ndefmessage |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


MediaQueryListEvent - Web APIs

MediaQueryListEvent
===================

The `MediaQueryListEvent` object stores information on the changes that have happened to a `MediaQueryList` object — instances are available as the event object on a function referenced by a `change` event.

Event

MediaQueryListEventConstructor
-----------

`MediaQueryListEvent()`

Creates a new `MediaQueryListEvent` instance.

Instance properties
-------------------

*The `MediaQueryListEvent` interface inherits properties from its parent interface, `Event`.*

`MediaQueryListEvent.matches` Read only

A boolean value that is `true` if the `document` currently matches the media query list, or `false` if not.

`MediaQueryListEvent.media` Read only

A string representing a serialized media query.

Instance methods
----------------

*The `MediaQueryListEvent` interface inherits methods from its parent interface, `Event`.*

Examples
--------

```js
const para = document.querySelector("p"); // This is the UI element where to display the text
const mql = window.matchMedia("(max-width: 600px)");

mql.addEventListener("change", (event) => {
  if (event.matches) {
    // The viewport is 600 pixels wide or less
    para.textContent = "This is a narrow screen — less than 600px wide.";
    document.body.style.backgroundColor = "red";
  } else {
    // The viewport is more than 600 pixels wide
    para.textContent = "This is a wide screen — more than 600px wide.";
    document.body.style.backgroundColor = "blue";
  }
});
```

Specifications
--------------

| Specification |
| --- |
| CSSOM View Module # the-mediaquerylist-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Media queries
* Using media queries from code
* `window.matchMedia()`
* `MediaQueryList`


SVGRadialGradientElement - Web APIs

SVGRadialGradientElement
========================

The **`SVGRadialGradientElement`** interface corresponds to the `<RadialGradient>` element.

EventTarget

Node

Element

SVGElement

SVGGradientElement

SVGRadialGradientElementInstance properties
-------------------

*This interface also inherits properties from its parent, `SVGGradientElement`.*

`SVGRadialGradientElement.cx` Read only

An `SVGAnimatedLength` corresponding to the `cx` attribute of the given `<RadialGradient>` element.

`SVGRadialGradientElement.cy` Read only

An `SVGAnimatedLength` corresponding to the `cy` attribute of the given `<RadialGradient>` element.

`SVGRadialGradientElement.r` Read only

An `SVGAnimatedLength` corresponding to the `r` attribute of the given `<RadialGradient>` element.

`SVGRadialGradientElement.fx` Read only

An `SVGAnimatedLength` corresponding to the `fx` attribute of the given `<RadialGradient>` element.

`SVGRadialGradientElement.fy` Read only

An `SVGAnimatedLength` corresponding to the `fy` attribute of the given `<RadialGradient>` element.

Instance methods
----------------

*This interface doesn't implement any specific methods, but inherits methods from its parent interface, `SVGGradientElement`.*

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 2 # InterfaceSVGRadialGradientElement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


TextFormatUpdateEvent - Web APIs

TextFormatUpdateEvent
=====================

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The **`TextFormatUpdateEvent`** interface is a `DOM event` that represents a list of text formats that an Input Method Editor (IME) window wants to apply to the text being composed in an editable region that's attached to an `EditContext` instance.

This interface inherits properties from `Event`.

Event

TextFormatUpdateEventConstructor
-----------

`TextFormatUpdateEvent()`
Experimental

Creates a new `TextFormatUpdateEvent` object.

Instance methods
----------------

`TextFormatUpdateEvent.getTextFormats`
Experimental

Returns an `Array` of `TextFormat` objects that represent the formats that the IME window wants to apply to the text.

Examples
--------

### Styling IME-composed text

In the following example, the `textformatupdate` event is used to update the formatting of the text in the editable region.

```html
<canvas id="editor-canvas"></canvas>
```

```js
const TEXT\_X = 10;
const TEXT\_Y = 10;

const canvas = document.getElementById("editor-canvas");
const ctx = canvas.getContext("2d");

const editContext = new EditContext();
canvas.editContext = editContext;

editContext.addEventListener("textformatupdate", (e) => {
  // Clear the canvas.
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Render the text.
  ctx.fillText(editContext.text, TEXT\_X, TEXT\_Y);
  console.log(`Rendering text: ${editContext.text}`);

  // Get the text formats that the IME window wants to apply.
  const formats = e.getTextFormats();

  // Iterate over the text formats
  for (const format of formats) {
    const { rangeStart, rangeEnd, underlineStyle, underlineThickness } = format;

    console.log(
      `Applying underline ${underlineThickness} ${underlineStyle} between ${rangeStart} and ${rangeEnd}.`,
    );

    const underlineXStart = ctx.measureText(
      editContext.text.substring(0, rangeStart),
    ).width;
    const underlineXEnd = ctx.measureText(
      editContext.text.substring(0, rangeEnd),
    ).width;
    const underlineY = TEXT\_Y + 3;

    // For brevity, this example only draws a simple underline.
    // Use underlineStyle and underlineThickness to draw the correct underline.

    ctx.beginPath();
    ctx.moveTo(TEXT\_X + underlineXStart, underlineY);
    ctx.lineTo(TEXT\_X + underlineXEnd, underlineY);
    ctx.stroke();
  }
});
```

Specifications
--------------

| Specification |
| --- |
| EditContext API # dom-textformatupdateevent |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


clearInterval() global function - Web APIs

clearInterval() global function
===============================

**Note:** This feature is available in Web Workers

 The global **`clearInterval()`** method cancels a timed, repeating action which
 was previously established by a call to `setInterval()`.
 If the parameter provided does not identify a previously established action,
 this method does nothing.

Syntax
------

```js
clearInterval(intervalID)
```

### Parameters

`intervalID`

 The identifier of the repeated action you want to cancel. This ID was returned by
 the corresponding call to `setInterval()`.

 It's worth noting that the pool of IDs used by
 `setInterval()` and
 `setTimeout()` are shared, which
 means you can technically use `clearInterval()` and
 `clearTimeout()` interchangeably.
 However, for clarity, you should avoid doing so.

### Return value

None (`undefined`).

Examples
--------

See the `setInterval()` examples.

Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-clearinterval-dev |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `setTimeout()`
* `setInterval()`
* `clearTimeout()`
* `Window.requestAnimationFrame()`


WebRTC API - Web APIs

WebRTC API
==========

**WebRTC** (Web Real-Time Communication) is a technology that enables Web applications and sites to capture and optionally stream audio and/or video media, as well as to exchange arbitrary data between browsers without requiring an intermediary. The set of standards that comprise WebRTC makes it possible to share data and perform teleconferencing peer-to-peer, without requiring that the user install plug-ins or any other third-party software.

WebRTC consists of several interrelated APIs and protocols which work together to achieve this. The documentation you'll find here will help you understand the fundamentals of WebRTC, how to set up and use both data and media connections, and more.

WebRTC concepts and usage
-------------------------

WebRTC serves multiple purposes; together with the Media Capture and Streams API, they provide powerful multimedia capabilities to the Web, including support for audio and video conferencing, file exchange, screen sharing, identity management, and interfacing with legacy telephone systems including support for sending DTMF (touch-tone dialing) signals. Connections between peers can be made without requiring any special drivers or plug-ins, and can often be made without any intermediary servers.

Connections between two peers are represented by the `RTCPeerConnection` interface. Once a connection has been established and opened using `RTCPeerConnection`, media streams (`MediaStream`s) and/or data channels (`RTCDataChannel`s) can be added to the connection.

Media streams can consist of any number of tracks of media information; tracks, which are represented by objects based on the `MediaStreamTrack` interface, may contain one of a number of types of media data, including audio, video, and text (such as subtitles or even chapter names). Most streams consist of at least one audio track and likely also a video track, and can be used to send and receive both live media or stored media information (such as a streamed movie).

You can also use the connection between two peers to exchange arbitrary binary data using the `RTCDataChannel` interface. This can be used for back-channel information, metadata exchange, game status packets, file transfers, or even as a primary channel for data transfer.

### Interoperability

WebRTC is in general well supported in modern browsers, but some incompatibilities remain. The adapter.js library is a shim to insulate apps from these incompatibilities.

WebRTC reference
----------------

Because WebRTC provides interfaces that work together to accomplish a variety of tasks, we have divided up the reference by category. Please see the sidebar for an alphabetical list.

### Connection setup and management

These interfaces, dictionaries, and types are used to set up, open, and manage WebRTC connections. Included are interfaces representing peer media connections, data channels, and interfaces used when exchanging information on the capabilities of each peer in order to select the best possible configuration for a two-way media connection.

#### Interfaces

`RTCPeerConnection`

Represents a WebRTC connection between the local computer and a remote peer. It is used to handle efficient streaming of data between the two peers.

`RTCDataChannel`

Represents a bi-directional data channel between two peers of a connection.

`RTCDataChannelEvent`

Represents events that occur while attaching a `RTCDataChannel` to a `RTCPeerConnection`. The only event sent with this interface is `datachannel`.

`RTCSessionDescription`

Represents the parameters of a session. Each `RTCSessionDescription` consists of a description `type` indicating which part of the offer/answer negotiation process it describes and of the SDP descriptor of the session.

`RTCStatsReport`

Provides information detailing statistics for a connection or for an individual track on the connection; the report can be obtained by calling `RTCPeerConnection.getStats()`.

`RTCIceCandidate`

Represents a candidate Interactive Connectivity Establishment (ICE) server for establishing an `RTCPeerConnection`.

`RTCIceTransport`

Represents information about an ICE transport.

`RTCPeerConnectionIceEvent`

Represents events that occur in relation to ICE candidates with the target, usually an `RTCPeerConnection`. Only one event is of this type: `icecandidate`.

`RTCRtpSender`

Manages the encoding and transmission of data for a `MediaStreamTrack` on an `RTCPeerConnection`.

`RTCRtpReceiver`

Manages the reception and decoding of data for a `MediaStreamTrack` on an `RTCPeerConnection`.

`RTCTrackEvent`

The interface used to represent a `track` event, which indicates that an `RTCRtpReceiver` object was added to the `RTCPeerConnection` object, indicating that a new incoming `MediaStreamTrack` was created and added to the `RTCPeerConnection`.

`RTCSctpTransport`

Provides information which describes a Stream Control Transmission Protocol (**SCTP**) transport and also provides a way to access the underlying Datagram Transport Layer Security (**DTLS**) transport over which SCTP packets for all of an `RTCPeerConnection`'s data channels are sent and received.

#### Events

`bufferedamountlow`

The amount of data currently buffered by the data channel—as indicated by its `bufferedAmount` property—has decreased to be at or below the channel's minimum buffered data size, as specified by `bufferedAmountLowThreshold`.

`close`

The data channel has completed the closing process and is now in the `closed` state. Its underlying data transport is completely closed at this point. You can be notified *before* closing completes by watching for the `closing` event instead.

`closing`

The `RTCDataChannel` has transitioned to the `closing` state, indicating that it will be closed soon. You can detect the completion of the closing process by watching for the `close` event.

`connectionstatechange`

The connection's state, which can be accessed in `connectionState`, has changed.

`datachannel`

A new `RTCDataChannel` is available following the remote peer opening a new data channel. This event's type is `RTCDataChannelEvent`.

`error`

An `RTCErrorEvent` indicating that an error occurred on the data channel.

`error`

An `RTCErrorEvent` indicating that an error occurred on the `RTCDtlsTransport`. This error will be either `dtls-failure` or `fingerprint-failure`.

`gatheringstatechange`

The `RTCIceTransport`'s gathering state has changed.

`icecandidate`

An `RTCPeerConnectionIceEvent` which is sent whenever the local device has identified a new ICE candidate which needs to be added to the local peer by calling `setLocalDescription()`.

`icecandidateerror`

An `RTCPeerConnectionIceErrorEvent` indicating that an error has occurred while gathering ICE candidates.

`iceconnectionstatechange`

Sent to an `RTCPeerConnection` when its ICE connection's state—found in the `iceconnectionstate` property—changes.

`icegatheringstatechange`

Sent to an `RTCPeerConnection` when its ICE gathering state—found in the `icegatheringstate` property—changes.

`message`

A message has been received on the data channel. The event is of type `MessageEvent`.

`negotiationneeded`

Informs the `RTCPeerConnection` that it needs to perform session negotiation by calling `createOffer()` followed by `setLocalDescription()`.

`open`

The underlying data transport for the `RTCDataChannel` has been successfully opened or re-opened.

`selectedcandidatepairchange`

The currently-selected pair of ICE candidates has changed for the `RTCIceTransport` on which the event is fired.

`track`

The `track` event, of type `RTCTrackevent` is sent to an `RTCPeerConnection` when a new track is added to the connection following the successful negotiation of the media's streaming.

`signalingstatechange`

Sent to the peer connection when its `signalingstate` has changed. This happens as a result of a call to either `setLocalDescription()` or `setRemoteDescription()`.

`statechange`

The state of the `RTCDtlsTransport` has changed.

`statechange`

The state of the `RTCIceTransport` has changed.

`statechange`

The state of the `RTCSctpTransport` has changed.

`rtctransform`

An encoded video or audio frame is ready to process using a transform stream in a worker.

#### Types

`RTCSctpTransport.state`

Indicates the state of an `RTCSctpTransport` instance.

### Identity and security

These APIs are used to manage user identity and security, in order to authenticate the user for a connection.

`RTCIdentityProvider`

Enables a user agent is able to request that an identity assertion be generated or validated.

`RTCIdentityAssertion`

Represents the identity of the remote peer of the current connection. If no peer has yet been set and verified this interface returns `null`. Once set it can't be changed.

`RTCIdentityProviderRegistrar`

Registers an identity provider (idP).

`RTCCertificate`

Represents a certificate that an `RTCPeerConnection` uses to authenticate.

### Telephony

These interfaces and events are related to interactivity with Public-Switched Telephone Networks (PSTNs). They're primarily used to send tone dialing sounds—or packets representing those tones—across the network to the remote peer.

#### Interfaces

`RTCDTMFSender`

Manages the encoding and transmission of Dual-Tone Multi-Frequency (DTMF) signaling for an `RTCPeerConnection`.

`RTCDTMFToneChangeEvent`

Used by the `tonechange` event to indicate that a DTMF tone has either begun or ended. This event does not bubble (except where otherwise stated) and is not cancelable (except where otherwise stated).

#### Events

`tonechange`

Either a new DTMF tone has begun to play over the connection, or the last tone in the `RTCDTMFSender`'s `toneBuffer` has been sent and the buffer is now empty. The event's type is `RTCDTMFToneChangeEvent`.

### Encoded Transforms

These interfaces and events are used to process incoming and outgoing encoded video and audio frames using a transform stream running in a worker.

#### Interfaces

`RTCRtpScriptTransform`

An interface for inserting transform stream(s) running in a worker into the RTC pipeline.

`RTCRtpScriptTransformer`

The worker-side counterpart of an `RTCRtpScriptTransform` that passes options from the main thread, along with a readable stream and writeable stream that can be used to pipe encoded frames through a `TransformStream`.

`RTCEncodedVideoFrame`

Represents an encoded video frame to be transformed in the RTC pipeline.

`RTCEncodedAudioFrame`

Represents an encoded audio frame to be transformed in the RTC pipeline.

#### Properties

`RTCRtpReceiver.transform`

A property used to insert a transform stream into the receiver pipeline for incoming encoded video and audio frames.

`RTCRtpSender.transform`

A property used to insert a transform stream into the sender pipeline for outgoing encoded video and audio frames.

#### Events

`rtctransform`

An RTC transform is ready to run in the worker, or an encoded video or audio frame is ready to process.

Guides
------

Introduction to WebRTC protocols

This article introduces the protocols on top of which the WebRTC API is built.

WebRTC connectivity

A guide to how WebRTC connections work and how the various protocols and interfaces can be used together to build powerful communication apps.

Lifetime of a WebRTC session

WebRTC lets you build peer-to-peer communication of arbitrary data, audio, or video—or any combination thereof—into a browser application. In this article, we'll look at the lifetime of a WebRTC session, from establishing the connection all the way through closing the connection when it's no longer needed.

Establishing a connection: The perfect negotiation pattern

**Perfect negotiation** is a design pattern which is recommended for your signaling process to follow, which provides transparency in negotiation while allowing both sides to be either the offerer or the answerer, without significant coding needed to differentiate the two.

Signaling and two-way video calling

A tutorial and example which turns a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling.

Codecs used by WebRTC

A guide to the codecs which WebRTC requires browsers to support as well as the optional ones supported by various popular browsers. Included is a guide to help you choose the best codecs for your needs.

Using WebRTC data channels

This guide covers how you can use a peer connection and an associated `RTCDataChannel` to exchange arbitrary data between two peers.

Using DTMF with WebRTC

WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the `RTCDTMFSender` interface. This guide shows how to do so.

Using WebRTC Encoded Transforms

This guide shows how a web application can modify incoming and outgoing WebRTC encoded video and audio frames, using a `TransformStream` running into a worker.

Tutorials
---------

Improving compatibility using WebRTC adapter.js

The WebRTC organization provides on GitHub the WebRTC adapter to work around compatibility issues in different browsers' WebRTC implementations. The adapter is a JavaScript shim which lets your code to be written to the specification so that it will "just work" in all browsers with WebRTC support.

A simple RTCDataChannel sample

The `RTCDataChannel` interface is a feature which lets you open a channel between two peers over which you may send and receive arbitrary data. The API is intentionally similar to the WebSocket API, so that the same programming model can be used for each.

Building an internet connected phone with Peer.js

This tutorial is a step-by-step guide on how to build a phone using Peer.js

Specifications
--------------

| Specification |
| --- |
| WebRTC: Real-Time Communication in Browsers  |
| Media Capture and Streams  |
| Media Capture from DOM Elements  |

### WebRTC-proper protocols

* Application Layer Protocol Negotiation for Web Real-Time Communications
* WebRTC Audio Codec and Processing Requirements
* RTCWeb Data Channels
* RTCWeb Data Channel Protocol
* Web Real-Time Communication (WebRTC): Media Transport and Use of RTP
* WebRTC Security Architecture
* Transports for RTCWEB
### Related supporting protocols

* Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal for Offer/Answer Protocol
* Session Traversal Utilities for NAT (STUN)
* URI Scheme for the Session Traversal Utilities for NAT (STUN) Protocol
* Traversal Using Relays around NAT (TURN) Uniform Resource Identifiers
* An Offer/Answer Model with Session Description Protocol (SDP)
* Session Traversal Utilities for NAT (STUN) Extension for Third Party Authorization
See also
--------

* `MediaDevices`
* `MediaStreamEvent`
* `MediaStreamTrack`
* `MessageEvent`
* `MediaStream`
* Media Capture and Streams API
* Firefox multistream and renegotiation for Jitsi Videobridge
* Peering Through the WebRTC Fog with SocketPeer
* Inside the Party Bus: Building a Web App with Multiple Live Video Streams + Interactive Graphics
* Web media technologies


SVGLengthList - Web APIs

SVGLengthList
=============

SVG length list interface
-------------------------

The `SVGLengthList` defines a list of `SVGLength` objects.

An `SVGLengthList` object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown.

An `SVGLengthList` is indexable and can be accessed like an array.

### Interface overview

|  |  |
| --- | --- |
| Also implement | *None* |
| Methods | * `void clear()`
* `SVGLength`
`initialize(in `SVGLength`
*newItem*)`
* `SVGLength`
`getItem(in unsigned long *index*)`
* `SVGLength`
`insertItemBefore(in `SVGLength`
*newItem*, in unsigned long *index*)`
* `SVGLength` `replaceItem(``in `SVGLength` *newItem*, in
unsigned long *index*``)`
* `SVGLength`
`removeItem(in unsigned long *index*)`
* `SVGLength`
`appendItem(in `SVGLength`
*newItem*)`
 |
| Properties | * readonly unsigned long `numberOfItems`
* readonly unsigned long
 `length`
Non-standard
 |
| Normative document | SVG 1.1 (2nd Edition) |

Instance properties
-------------------

| Name | Type | Description |
| --- | --- | --- |
| `numberOfItems` | unsigned long | The number of items in the list. |
| `length`
Non-standard
 | unsigned long | The number of items in the list. |

Instance methods
----------------

| Name & Arguments | Return | Description |
| --- | --- | --- |
| `**clear**()` | *void* |
 Clears all existing current items from the list, with the result being
 an empty list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**initialize**(``in `SVGLength` *newItem*``)` | `SVGLength` |
 Clears all existing current items from the list and re-initializes the
 list to hold the single item specified by the parameter. If the
 inserted item is already in a list, it is removed from its previous
 list before it is inserted into this list. The inserted item is the
 item itself and not a copy. The return value is the item inserted into
 the list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**getItem**(in unsigned long *index*)` | `SVGLength` |
 Returns the specified item from the list. The returned item is the
 item itself and not a copy. Any changes made to the item are
 immediately reflected in the list. The first item is number 0.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**insertItemBefore**(in
`SVGLength` *newItem*, in unsigned
long *index*)` | `SVGLength` |
 Inserts a new item into the list at the specified position. The first
 item is number 0. If `newItem` is already in a list, it is
 removed from its previous list before it is inserted into this list.
 The inserted item is the item itself and not a copy. If the item is
 already in this list, note that the index of the item to insert before
 is before the removal of the item. If the `index` is equal
 to 0, then the new item is inserted at the front of the list. If the
 index is greater than or equal to `numberOfItems`, then the
 new item is appended to the end of the list.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |
| `**replaceItem**(``in `SVGLength` *newItem*, in unsigned
long *index*``)` | `SVGLength` |
 Replaces an existing item in the list with a new item. If
 `newItem` is already in a list, it is removed from its
 previous list before it is inserted into this list. The inserted item
 is the item itself and not a copy. If the item is already in this
 list, note that the index of the item to replace is before the removal
 of the item.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
* a `DOMException` with code
 `INDEX_SIZE_ERR` is raised if the index number is greater
 than or equal to `numberOfItems`.
 |
| `**removeItem**(in unsigned long *index*)` | `SVGLength` | Removes an existing item from the list.
**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
* a `DOMException` with code
 `INDEX_SIZE_ERR` is raised if the index number is greater
 than or equal to `numberOfItems`.
 |
| `**appendItem**(in `SVGLength`
*newItem*)` | `SVGLength` |
 Inserts a new item at the end of the list. If `newItem` is
 already in a list, it is removed from its previous list before it is
 inserted into this list. The inserted item is the item itself and not
 a copy.

**Exceptions:*** a `DOMException` with code
 `NO_MODIFICATION_ALLOWED_ERR` is raised when the list
 corresponds to a read only attribute or when the object itself is
 read only.
 |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


MediaSession - Web APIs

MediaSession
============

The **`MediaSession`** interface of the Media Session API allows a web page to provide custom behaviors for standard media playback interactions, and to report metadata that can be sent by the user agent to the device or operating system for presentation in standardized user interface elements.

For example, a smartphone might have a standard panel in its lock screen that provides controls for media playback and information display. A browser on the device can use `MediaSession` to make browser playback controllable from that standard/global user interface.

Instance properties
-------------------

`metadata`

Returns an instance of `MediaMetadata`, which contains rich media metadata for display in a platform UI.

`playbackState`

Indicates whether the current media session is playing. Valid values are `none`, `paused`, or `playing`.

Instance methods
----------------

`setActionHandler()`

Sets an action handler for a media session action, such as play or pause.

`setCameraActive()`
Experimental

Indicates to the user agent whether the user's camera is considered to be active.

`setMicrophoneActive()`
Experimental

Indicates to the user agent whether the user's microphone is considered to be currently muted.

`setPositionState()`

Sets the current playback position and speed of the media currently being presented.

Examples
--------

### Setting up action handlers for a music player

The following example creates a new media session and assigns action handlers to it:

```js
if ("mediaSession" in navigator) {
  navigator.mediaSession.metadata = new MediaMetadata({
    title: "Unforgettable",
    artist: "Nat King Cole",
    album: "The Ultimate Collection (Remastered)",
    artwork: [
      {
        src: "https://dummyimage.com/96x96",
        sizes: "96x96",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/128x128",
        sizes: "128x128",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/192x192",
        sizes: "192x192",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/256x256",
        sizes: "256x256",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/384x384",
        sizes: "384x384",
        type: "image/png",
      },
      {
        src: "https://dummyimage.com/512x512",
        sizes: "512x512",
        type: "image/png",
      },
    ],
  });

  navigator.mediaSession.setActionHandler("play", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("pause", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("stop", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekbackward", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekforward", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("seekto", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("previoustrack", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("nexttrack", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("skipad", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("togglecamera", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("togglemicrophone", () => {
    /\* Code excerpted. \*/
  });
  navigator.mediaSession.setActionHandler("hangup", () => {
    /\* Code excerpted. \*/
  });
}
```

The following example sets up two functions for playing and pausing, then uses them as callbacks with the relevant action handlers.

```js
const actionHandlers = [
  // play
  [
    "play",
    async () => {
      // play our audio
      await audioEl.play();
      // set playback state
      navigator.mediaSession.playbackState = "playing";
      // update our status element
      updateStatus(allMeta[index], "Action: play | Track is playing…");
    },
  ],
  [
    "pause",
    () => {
      // pause out audio
      audioEl.pause();
      // set playback state
      navigator.mediaSession.playbackState = "paused";
      // update our status element
      updateStatus(allMeta[index], "Action: pause | Track has been paused…");
    },
  ],
];

for (const [action, handler] of actionHandlers) {
  try {
    navigator.mediaSession.setActionHandler(action, handler);
  } catch (error) {
    console.log(`The media session action "${action}" is not supported yet.`);
  }
}
```

### Using action handlers to control a slide presentation

The `"previousslide"` and `"nextslide"` action handlers can be used to handle moving forward and backward through a slide presentation, for example when the user puts their presentation into a Picture-in-Picture window, and presses the browser-supplied controls for navigating through slides.

```js
try {
  navigator.mediaSession.setActionHandler("previousslide", () => {
    log('> User clicked "Previous Slide" icon.');
    if (slideNumber > 1) slideNumber--;
    updateSlide();
  });
} catch (error) {
  log('Warning! The "previousslide" media session action is not supported.');
}

try {
  navigator.mediaSession.setActionHandler("nextslide", () => {
    log('> User clicked "Next Slide" icon.');
    slideNumber++;
    updateSlide();
  });
} catch (error) {
  log('Warning! The "nextslide" media session action is not supported.');
}
```

See Presenting Slides / Media Session Sample for a working example.

Specifications
--------------

| Specification |
| --- |
| Media Session # the-mediasession-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


XRView - Web APIs

XRView
======

**Secure context:** This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

**Experimental:** **This is an experimental technology**
Check the Browser compatibility table carefully before using this in production.

The WebXR Device API's **`XRView`** interface describes a single view into the XR scene for a specific frame, providing orientation and position information for the viewpoint. You can think of it as a description of a specific eye or camera and how it views the world. A 3D frame will involve two views, one for each eye, separated by an appropriate distance which approximates the distance between the viewer's eyes. This allows the two views, when projected in isolation into the appropriate eyes, to simulate a 3D world.

Instance properties
-------------------

`eye` Read only
Experimental

Which of the two eyes (`left`) or (`right`) for which this `XRView` represents the perspective. This value is used to ensure that any content which is pre-rendered for presenting to a specific eye is distributed or positioned correctly. The value can also be `none` if the `XRView` is presenting monoscopic data (such as a 2D image, a fullscreen view of text, or a close-up view of something that doesn't need to appear in 3D).

`isFirstPersonObserver` Read only
Experimental

Returns a boolean indicating if the `XRView` is a first-person observer view.

`projectionMatrix` Read only
Experimental

The projection matrix that will transform the scene to appear correctly given the point-of-view indicated by `eye`. This matrix should be used directly in order to avoid presentation distortions that may lead to potentially serious user discomfort.

`recommendedViewportScale` Read only
Experimental

The recommended viewport scale value that you can use for `requestViewportScale()` if the user agent has such a recommendation; `null` otherwise.

`transform` Read only
Experimental

An `XRRigidTransform` which describes the current position and orientation of the viewpoint in relation to the `XRReferenceSpace` specified when `getViewerPose()` was called on the `XRFrame` being rendered.

Instance methods
----------------

`requestViewportScale()` Read only
Experimental

Requests that the user agent should set the requested viewport scale for this viewport to the requested value.

Usage notes
-----------

### Positions and number of XRViews per frame

While rendering a scene, the set of views that are used to render the scene for the viewer as of the current frame are obtained by calling the `XRFrame` object's `getViewerPose()` method to get the `XRViewerPose` representing (in essence) the position of the viewer's head. That object's `views` property is a list of all of the `XRView` objects representing the viewpoints which can be used to construct the scene for presentation to the user.

It's possible to have `XRView` objects which represent overlapping regions as well as entirely disparate regions; in a game, you might have views that can be presented to observe a remote site using a security camera or other device, for example. In other words, don't assume there are exactly two views on a given viewer; there can be as few as one (such as when rendering the scene in `inline` mode, and potentially many (especially if the field of view is very large). There might also be views representing observers watching the action, or other viewpoints not directly associated with a player's eye.

In addition, the number of views can change at any time, depending on the needs of the time. So you should process the view list every time without making assumptions based on previous frames.

All positions and orientations within the views for a given `XRViewerPose` are specified in the reference space that was passed to `XRFrame.getViewerPose()`; this is called the **viewer reference space**. The `transform` property describes the position and orientation of the eye or camera represented by the `XRView`, given in that reference space.

### The destination rendering layer

To render a frame, you iterate over the `XRViewerPose`'s views, rendering each of them into the appropriate viewport within the frame's `XRWebGLLayer`. Currently, the specification (and therefore all current implementations of WebXR) is designed around rendering every `XRView` into a single `XRWebGLLayer`, which is then presented on the XR device with half used for the left eye and half for the right eye. The `XRViewport` for each view is used to position the rendering into the correct half of the layer.

If in the future it becomes possible for each view to render into a different layer, there would have to be changes made to the API, so it's safe for now to assume that all views will render into the same layer.

Examples
--------

### Preparing to render every view for a pose

To draw everything the user sees, each frame requires iterating over the list of views returned by the `XRViewerPose` object's `views` list:

```js
for (const view of pose.views) {
  const viewport = glLayer.getViewport(view);

  gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);

  // Draw the scene; the eye being drawn is identified
  // by view.eye.
}
```

### Special view transforms

There are a few special transforms that are used on the view while rendering and lighting a scene.

#### Model view matrix

The **model view matrix** is a matrix which defines the position of an object relative to the space in which it's located: If `objectMatrix` is a transform applied to the object to provide its basic position and rotation, then the model view matrix can be computed by multiplying the object's matrix by the inverse of the view transform matrix, like this:

```js
mat4.multiply(modelViewMatrix, view.transform.inverse.matrix, objectMatrix);
```

#### Normal matrix

The model view's **normal matrix** is used when lighting the scene, in order to transform each surface's normal vectors to ensure that the light is reflected in the correct direction given the orientation and position of the surface relative to the light source or sources. It's computed by inverting then transposing the model view matrix:

```js
mat4.invert(normalMatrix, modelViewMatrix);
mat4.transpose(normalMatrix, normalMatrix);
```

### Teleporting an object

To programmatically move and/or rotate (often referred to as **teleporting**) an object, you need to create a new reference space for that object which applies a transform that encapsulates the desired changes. The `createTeleportTransform()` function returns the transform needed to move and rotate an object whose current situation is described by the reference space `refSpace` to a new position and orientation which is computed using previously recorded mouse and keyboard input data which has generated offsets for yaw, pitch, and position along all three axes.

```js
function applyMouseMovement(refSpace) {
  if (
    !mouseYaw &&
    !mousePitch &&
    !axialDistance &&
    !transverseDistance &&
    !verticalDistance
  ) {
    return refSpace;
  }

  // Compute the quaternion used to rotate the image based
  // on the pitch and yaw.

  quat.identity(inverseOrientation);
  quat.rotateX(inverseOrientation, inverseOrientation, -mousePitch);
  quat.rotateY(inverseOrientation, inverseOrientation, -mouseYaw);

  // Compute the true "up" vector for our object.

  vec3.cross(vecX, vecY, cubeOrientation);
  vec3.cross(vecY, cubeOrientation, vecX);

  // Now compute the transform that teleports the object to the
  // specified point and save a copy of it to display to the user
  // later; otherwise we probably wouldn't need to save mouseMatrix
  // at all.

  let newTransform = new XRRigidTransform(
    { x: transverseDistance, y: verticalDistance, z: axialDistance },
    {
      x: inverseOrientation[0],
      y: inverseOrientation[1],
      z: inverseOrientation[2],
      w: inverseOrientation[3],
    },
  );
  mat4.copy(mouseMatrix, newTransform.matrix);

  // Create a new reference space that transforms the object to the new
  // position and orientation, returning the new reference space.

  return refSpace.getOffsetReferenceSpace(newTransform);
}
```

This code is broken into four sections. In the first, the quaternion `inverseOrientation` is computed. This represents the rotation of the object given the values of `mousePitch` (rotation around the object's reference's space's X axis) and `mouseYaw` (rotation around the object's Y axis).

The second section computes the "up" vector for the object. This vector indicates the direction which is "up" in the scene overall, but in the object's reference space.

The third section creates the new `XRRigidTransform`, specifying a point providing the offsets along the three axes as the first parameter, and the orientation quaternion as the second parameter. The returned object's `matrix` property is the actual matrix that transforms points from the scene's reference space to the object's new position.

Finally, a new reference space is created to describe the relationship between the two reference spaces fully. That reference space is returned to the caller.

To use this function, we pass the returned reference space into `XRFrame.getPose()` or `getViewerPose()`, as appropriate for your needs. The returned `XRPose` will then be used to render the scene for the current frame.

You can find a more extensive and complete example in our article Movement, orientation, and motion.

Specifications
--------------

| Specification |
| --- |
| WebXR Device API # xrview-interface |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.


SVGCursorElement - Web APIs

SVGCursorElement
================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The **`SVGCursorElement`** interface provides access to the properties of `<cursor>` elements, as well as methods to manipulate them.

Instance properties
-------------------

*This interface also inherits properties from its parent, `SVGElement`.*

`SVGCursorElement.x` Read only

An `SVGAnimatedLength` corresponding to the `x` attribute of the given `<cursor>` element.

`SVGCursorElement.y` Read only

An `SVGAnimatedLength` corresponding to the `y` attribute of the given `<cursor>` element.

Instance methods
----------------

*This interface doesn't implement any specific methods, but inherits methods from its parent, `SVGElement`.*

Specifications
--------------

| Specification |
| --- |
| Scalable Vector Graphics (SVG) 1.1 (Second Edition) # InterfaceSVGCursorElement |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* `<cursor>`


PerformanceNavigation - Web APIs

PerformanceNavigation
=====================

**Deprecated:** This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The legacy **`PerformanceNavigation`** interface represents information about how the navigation to the current document was done.

**Warning:** This interface is deprecated in the Navigation Timing Level 2 specification.
 Please use the `PerformanceNavigationTiming` interface instead.

An object of this type can be obtained by calling the `Performance.navigation` read-only attribute.

Instance properties
-------------------

*The `PerformanceNavigation` interface doesn't inherit any properties.*

`PerformanceNavigation.type` Read only
Deprecated

An `unsigned short` which indicates how the navigation to this page was done. Possible values are:

`TYPE_NAVIGATE` (0)

The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.

`TYPE_RELOAD` (1)

The page was accessed by clicking the Reload button or via the `Location.reload()` method.

`TYPE_BACK_FORWARD` (2)

The page was accessed by navigating into the history.

`TYPE_RESERVED` (255)

Any other way.

`PerformanceNavigation.redirectCount` Read only
Deprecated

An `unsigned short` representing the number of REDIRECTs done before reaching the page.

Instance methods
----------------

*The `Performance` interface doesn't inherit any methods.*

`PerformanceNavigation.toJSON()`
Deprecated

A serializer returning a JSON object representing the `PerformanceNavigation` object.

Specifications
--------------

 This feature is no longer on track to become a standard, as the Navigation Timing specification has marked it as deprecated.
 Use the `PerformanceNavigationTiming` interface instead.

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* The `Performance` that allows access to an object of this type.
* `PerformanceNavigationTiming` (part of Navigation Timing Level 2) that has superseded this API.