Window: scrollY property - Web APIs

Window: scrollY property
========================

 The read-only **`scrollY`** property
 of the `Window` interface returns the number of pixels that the document
 is currently scrolled vertically.

 This value is subpixel precise in modern
 browsers, meaning that it isn't necessarily a whole number. You can get the number of
 pixels the document is scrolled horizontally from the `scrollX` property.

Value
-----

 In practice, the returned value is a double-precision floating-point value with the range of
 2^(-1022) to 2^(+1023). It indicates the number of pixels the document is currently scrolled
 vertically from the origin, where a positive value means the content is scrolled to upward.
 If the document is rendered on a subpixel-precise device, then the returned value is also
 subpixel-precise and may contain a decimal component. If the document isn't scrolled at all
 up or down, then `scrollY` is 0.

**Note:** If you need an integer value, you can use `Math.round()` to round it off.

 In more technical terms, `scrollY` returns the Y coordinate of the top edge
 of the current viewport. If there is no viewport, the returned value is
 0.

Examples
--------

```js
// make sure and go down to the second page
if (window.scrollY) {
  window.scroll(0, 0); // reset the scroll position to the top left of the document.
}

window.scrollByPages(1);
```

Notes
-----

 Use this property to check that the document hasn't already been scrolled when using
 relative scroll functions such as `scrollBy()`,
 `scrollByLines()`, or
 `scrollByPages()`.

 The `pageYOffset` property is an alias for the `scrollY`
 property:

```js
window.pageYOffset === window.scrollY; // always true
```

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

| Specification |
| --- |
| CSSOM View Module # dom-window-scrolly |

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

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

See also
--------

* `window.scrollX`


Window: scrollBy() method - Web APIs

Window: scrollBy() method
=========================

 The **`Window.scrollBy()`** method scrolls the document in the
 window by the given amount.

Syntax
------

```js
scrollBy(x-coord, y-coord)
scrollBy(options)
```

### Parameters

* `x-coord` is the horizontal pixel value that you want to scroll by.
* `y-coord` is the vertical pixel value that you want to scroll by.

- or -

`options`

A dictionary containing the following parameters:

`top`

Specifies the number of pixels along the Y axis to scroll the window or element.

`left`

Specifies the number of pixels along the X axis to scroll the window or element.

`behavior`

Specifies whether the scrolling should animate smoothly (`smooth`), happen instantly in a single jump (`instant`), or let the browser choose (`auto`, default).

### Return value

None (`undefined`).

Examples
--------

To scroll down one page:

```js
window.scrollBy(0, window.innerHeight);
```

To scroll up:

```js
window.scrollBy(0, -window.innerHeight);
```

Using `options`:

```js
window.scrollBy({
  top: 100,
  left: 100,
  behavior: "smooth",
});
```

Notes
-----

`window.scrollBy()` scrolls by a particular amount, whereas
 `window.scroll()` scrolls to an absolute position in the document. See also
 `window.scrollByLines()` and `window.scrollByPages()`.

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

| Specification |
| --- |
| CSSOM View Module # dom-window-scrollby |

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

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


Window: queryLocalFonts() method - Web APIs

Window: queryLocalFonts() method
================================

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

The **`window.queryLocalFonts()`** method returns a `Promise` that fulfills with an array of `FontData` objects representing the font faces available locally.

To use this method, the user must grant permission to access `local-fonts` (permission status can be queried via the Permissions API). In addition, this feature may be blocked by a Permissions Policy set on your server.

Syntax
------

```js
queryLocalFonts(options)
```

### Parameters

`options` Optional

Contains optional configuration parameters. Currently only one property is defined:

`postscriptNames` Optional

An array of font PostScript names. If this is specified, only fonts with PostScript names matching those in the array will be included in the results; if not, all fonts will be included in the results.

### Return value

A `Promise` that fulfills with an array of `FontData` objects representing the font faces available locally.

### Exceptions

`NotAllowedError` `DOMException`

The user chose to deny permission to use this feature when presented with the browser's permission prompt after the method was first invoked.

`SecurityError` `DOMException`

Use of this feature was blocked by a Permissions Policy, or it was not called via a user interaction such as a button press, or current origin is an opaque origin.

Examples
--------

For a working live demo, see Font Select Demo.

### Font enumeration

The following snippet will query for all available fonts and log metadata. This could be used, for example, to populate a font picker control.

```js
async function logFontData() {
  try {
    const availableFonts = await window.queryLocalFonts();
    for (const fontData of availableFonts) {
      console.log(fontData.postscriptName);
      console.log(fontData.fullName);
      console.log(fontData.family);
      console.log(fontData.style);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

### Limiting returned results

To limit the returned font data to only a specific list of font faces, use the `postscriptNames` option.

```js
async function returnSpecificFonts() {
  const availableFonts = await window.queryLocalFonts({
    postscriptNames: ["Verdana", "Verdana-Bold", "Verdana-Italic"],
  });

  return availableFonts;
}
```

### Accessing low-level data

The `blob()` method provides access to low-level SFNT data — this is a font file format that can contain other font formats, such as PostScript, TrueType, OpenType, or Web Open Font Format (WOFF).

```js
async function computeOutlineFormat() {
  try {
    const availableFonts = await window.queryLocalFonts({
      postscriptNames: ["ComicSansMS"],
    });
    for (const fontData of availableFonts) {
      // `blob()` returns a Blob containing valid and complete
      // SFNT-wrapped font data.
      const sfnt = await fontData.blob();
      // Slice out only the bytes we need: the first 4 bytes are the SFNT
      // version info.
      // Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
      const sfntVersion = await sfnt.slice(0, 4).text();

      let outlineFormat = "UNKNOWN";
      switch (sfntVersion) {
        case "\x00\x01\x00\x00":
        case "true":
        case "typ1":
          outlineFormat = "truetype";
          break;
        case "OTTO":
          outlineFormat = "cff";
          break;
      }
      console.log("Outline format:", outlineFormat);
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}
```

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

| Specification |
| --- |
| Local Font Access # dom-window-querylocalfonts |

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

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

See also
--------

* Local Font Access API
* Use advanced typography with local fonts
* `@font-face`


Window: orientation property - Web APIs

Window: orientation property
============================

**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.

Returns the orientation in degrees (in 90-degree increments) of the viewport relative to the device's natural orientation.

Its only possible values are `-90`, `0`, `90`, and `180`. Positive values are counterclockwise; negative values are clockwise.

This property is deprecated. Use the `Screen.orientation` property instead, available on the `window.screen` property.

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

| Specification |
| --- |
| Compatibility Standard # dfn-window-orientation-angle |

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

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


Window: frames property - Web APIs

Window: frames property
=======================

 Returns the window itself, which is an array-like object, listing the direct sub-frames
 of the current window.

Value
-----

 A list of frame objects. It is similar to an
 array in that it has a `length` property and its items can be accessed
 using the `[i]` notation.

* `frameList === window` evaluates to true.
* Each item in the `window.frames` pseudo-array represents the `Window`
 object corresponding to the given `<frame>`'s or
 `<iframe>`'s content, not the `frame` or `iframe` DOM element (i.e.,
 `window.frames[0]` is the same thing as
 `document.getElementsByTagName("iframe")[0].contentWindow`).
* For more details about the returned value, refer to this thread on mozilla.dev.platform.
Examples
--------

```js
const frames = window.frames; // or const frames = window.parent.frames;
for (let i = 0; i < frames.length; i++) {
  // do something with each subframe as frames[i]
  frames[i].document.body.style.background = "red";
}
```

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

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

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

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


Window: customElements property - Web APIs

Window: customElements property
===============================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`customElements`** read-only property of the `Window` interface returns a reference to the `CustomElementRegistry` object, which can be used to register new custom elements and get information about previously registered custom elements.

Examples
--------

The most common example you'll see of this property being used is to get access to the `CustomElementRegistry.define()` method to define and register a new custom element, e.g.:

```js
let customElementRegistry = window.customElements;
customElementRegistry.define("my-custom-element", MyCustomElement);
```

However, it is usually shortened to something like the following:

```js
customElements.define(
  "element-details",
  class extends HTMLElement {
    constructor() {
      super();
      const template = document.getElementById(
        "element-details-template",
      ).content;
      const shadowRoot = this.attachShadow({ mode: "open" }).appendChild(
        template.cloneNode(true),
      );
    }
  },
);
```

See our web-components-examples repo for more usage examples.

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

| Specification |
| --- |
| HTML Standard # dom-window-customelements |

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

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


Window: self property - Web APIs

Window: self property
=====================

The **`Window.self`** read-only property returns the window itself, as a WindowProxy. It can be used with dot notation on a `window` object (that is, `window.self`) or standalone (`self`). The advantage of the standalone notation is that a similar notation exists for non-window contexts, such as in Web Workers. By using `self`, you can refer to the global scope in a way that will work not only in a window context (`self` will resolve to `window.self`) but also in a worker context (`self` will then resolve to `WorkerGlobalScope.self`).

Value
-----

A WindowProxy object.

Examples
--------

Uses of `window.self` like the following could just as well be replaced by `window`.

```js
if (window.parent.frames[0] !== window.self) {
  // this window is not the first frame in the list
}
```

Furthermore, when executing in the active document of a browsing context, `window` is a reference to the current global object and thus all of the following are equivalent:

```js
const w1 = window;
const w2 = self;
const w3 = window.window;
const w4 = window.self;
// w1, w2, w3, w4 all strictly equal, but only w2 will function in workers
```

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

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

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

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

See also
--------

* Its `Worker` equivalent, `WorkerGlobalScope.self`.


Window: console property - Web APIs

Window: console property
========================

The **`Window.console`** property returns a reference to the `console` object, which provides methods for logging information to the browser's console. These methods are intended for debugging purposes only and should not be relied on for presenting information to end users.

Examples
--------

### Logging to console

The first example logs text to the console.

```js
console.log("An error occurred while loading the content");
```

The next example logs an object to the console, with the object's fields expandable using disclosure widgets:

```js
console.dir(someObject);
```

For more examples, see the Examples section of the `console` article.

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

| Specification |
| --- |
| Console Standard  |

**Note:** Currently there are many implementation differences among browsers, but work is being done to bring them together and make them more consistent with one another.


Window: originAgentCluster property - Web APIs

Window: originAgentCluster property
===================================

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

The **`originAgentCluster`** read-only property of the `Window` interface returns `true` if this window belongs to an *origin-keyed agent cluster*: this means that the operating system has provided dedicated resources (for example an operating system process) to this window's origin that are not shared with windows from other origins.

Otherwise this property returns `false`.

Windows that are part of an origin-keyed agent cluster are subjects to some additional restrictions, compared with windows that are not. In particular, they cannot:

* Set `Document.domain`, which is a legacy feature that normally allows same-site cross-origin pages to synchronously access each other's DOM.
* Send `WebAssembly.Module` objects to other same-site cross-origin pages via `Window.postMessage()`.
* Send `SharedArrayBuffer` or `WebAssembly.Memory` objects to other same-site cross-origin pages.

To request that the browser assign this window to an origin-keyed agent cluster, the server must send the `Origin-Agent-Cluster` response header.

Note that the origin-keyed agent cluster feature is only supported in secure contexts. If a site is not a secure context, the `window.originAgentCluster` will always return `false`.

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

| Specification |
| --- |
| HTML Standard # origin-keyed-agent-clusters |

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

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

See also
--------

* `Origin-Agent-Cluster` HTTP response header
* Requesting performance isolation with the Origin-Agent-Cluster header


Window: requestFileSystem() method - Web APIs

Window: requestFileSystem() method
==================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The non-standard `Window` method
 **`requestFileSystem()`** method is a Google Chrome-specific
 method which lets a website or app gain access to a sandboxed file system for its own
 use. The returned `FileSystem` is then available for use with the other file system APIs.

**Note:** This method is prefixed with `webkit` in all browsers that implement it.

Syntax
------

```js
requestFileSystem(type, size, successCallback)
requestFileSystem(type, size, successCallback, errorCallback)
```

### Parameters

`type`

 The type of storage to request. Specify `Window.TEMPORARY` if it's
 acceptable for the browser to delete the files at its own discretion, such as if
 storage space runs low, or `Window.PERSISTENT` if you need the files to
 remain in place unless the user or the website or app explicitly permit it.
 Persistent storage requires that the user grant the site quota.

`size`

The amount of storage space you wish to have allocated for your app's use.

`successCallback`

 A function which is invoked when the file system has been successfully obtained. The
 callback receives a single parameter: a `FileSystem` object representing
 the file system the app has permission to use.

`errorCallback` Optional

 An optional parameter specifying a function which is called if an error occurs while
 attempting to obtain the file system, or if the user denies permission to create or
 access the file system. The callback receives as input a single parameter: a
 `FileError` object describing the error.

### Return value

None (`undefined`).

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

As this method was removed from the File and Directory Entries API proposal, it has no official W3C or WHATWG specification. It is no longer on track to become a standard.

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

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

See also
--------

* File and Directory Entries API support in Firefox


Window: scrollbars property - Web APIs

Window: scrollbars property
===========================

Returns the `scrollbars` object.

This is one of a group of `Window` properties that contain a boolean `visible` property, that used to represent whether or not a particular part of a web browser's user interface was visible.

For privacy and interoperability reasons, the value of the `visible` property is now `false` if this `Window` is a popup, and `true` otherwise.

Value
-----

An object containing a single property:

`visible` Read only

A boolean property, `false` if this `Window` is a popup, and `true` otherwise.

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

| Specification |
| --- |
| HTML Standard # dom-window-scrollbars-dev |

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

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

See also
--------

* `window.locationbar`
* `window.menubar`
* `window.personalbar`
* `window.statusbar`
* `window.toolbar`


Window: unhandledrejection event - Web APIs

Window: unhandledrejection event
================================

The **`unhandledrejection`** event is sent to the global scope of a script when a JavaScript `Promise` that has no rejection handler is rejected; typically, this is the `window`, but may also be a `Worker`.

This is useful for debugging and for providing fallback error handling for unexpected situations.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("unhandledrejection", (event) => {});
onunhandledrejection = (event) => {};
```

Event type
----------

A `PromiseRejectionEvent`. Inherits from `Event`.

Event

PromiseRejectionEventEvent properties
----------------

`PromiseRejectionEvent.promise` Read only

The JavaScript `Promise` that was rejected.

`PromiseRejectionEvent.reason` Read only

A value or `Object` indicating why the promise was rejected, as passed to `Promise.reject()`.

Event handler aliases
---------------------

In addition to the `Window` interface, the event handler property `onunhandledrejection` is also available on the following targets:

* `HTMLBodyElement`
* `HTMLFrameSetElement`
* `SVGSVGElement`
Usage notes
-----------

Allowing the `unhandledrejection` event to bubble will eventually result in an error message being output to the console. You can prevent this by calling `preventDefault()` on the `PromiseRejectionEvent`; see Preventing default handling below for an example.

Because this event can leak data, `Promise` rejections that originate from a cross-origin script won't fire this event.

Examples
--------

### Basic error logging

This example logs information about the unhandled promise rejection to the console.

```js
window.addEventListener("unhandledrejection", (event) => {
  console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
});
```

You can also use the `onunhandledrejection` event handler property to set up the event listener:

```js
window.onunhandledrejection = (event) => {
  console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
};
```

### Preventing default handling

Many environments (such as Node.js) report unhandled promise rejections to the console by default. You can prevent that from happening by adding a handler for `unhandledrejection` events that—in addition to any other tasks you wish to perform—calls `preventDefault()` to cancel the event, preventing it from bubbling up to be handled by the runtime's logging code. This works because `unhandledrejection` is cancelable.

```js
window.addEventListener("unhandledrejection", (event) => {
  // code for handling the unhandled rejection
  // …

  // Prevent the default handling (such as outputting the
  // error to the console)

  event.preventDefault();
});
```

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

| Specification |
| --- |
| HTML Standard # event-unhandledrejection |
| HTML Standard # handler-window-onunhandledrejection |

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

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

See also
--------

* Promise rejection events
* `rejectionhandled` event
* `Promise`


Window: orientationchange event - Web APIs

Window: orientationchange event
===============================

**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 `orientationchange` event is fired when the orientation of the device has changed.

This event is not cancelable and does not bubble.

This event is deprecated. Listen for the `change` event of the `ScreenOrientation` interface instead.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("orientationchange", (event) => {});

onorientationchange = (event) => {};
```

Event type
----------

A generic `Event`.

Example
-------

You can use the `orientationchange` event in an `addEventListener` method:

```js
window.addEventListener("orientationchange", (event) => {
  console.log(
    `the orientation of the device is now ${event.target.screen.orientation.angle}`,
  );
});
```

Or use the `onorientationchange` event handler property:

```js
window.onorientationchange = (event) => {
  console.log(
    `the orientation of the device is now ${event.target.screen.orientation.angle}`,
  );
};
```

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

| Specification |
| --- |
| Compatibility Standard # event-orientationchange |

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

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


Window: menubar property - Web APIs

Window: menubar property
========================

Returns the `menubar` object.

This is one of a group of `Window` properties that contain a boolean `visible` property, that used to represent whether or not a particular part of a web browser's user interface was visible.

For privacy and interoperability reasons, the value of the `visible` property is now `false` if this `Window` is a popup, and `true` otherwise.

Value
-----

An object containing a single property:

`visible` Read only

A boolean property, `false` if this `Window` is a popup, and `true` otherwise.

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

| Specification |
| --- |
| HTML Standard # dom-window-menubar-dev |

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

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

See also
--------

* `window.locationbar`
* `window.personalbar`
* `window.scrollbars`
* `window.statusbar`
* `window.toolbar`


Window: scrollMaxY property - Web APIs

Window: scrollMaxY property
===========================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`Window.scrollMaxY`** read-only property returns the
 maximum number of pixels that the document can be scrolled vertically.

Value
-----

A number.

Examples
--------

```js
// Scroll to the bottom of the page
let maxY = window.scrollMaxY;

window.scrollTo(0, maxY);
```

Notes
-----

 Do not use this property to get the total document height, which is not equivalent to
 `window.innerHeight` + window.scrollMaxY, because
 `window.innerHeight` includes the width of any visible horizontal
 scrollbar, thus the result would exceed the total document height by the width of any
 visible horizontal scrollbar. Instead use
 `document.body.scrollHeight`. See also
 `window.scrollMaxX` and `window.scrollTo`.

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

This is not part of any specification.

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

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


Window: gamepadconnected event - Web APIs

Window: gamepadconnected event
==============================

The `gamepadconnected` event is fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.

The event will not fire if disallowed by the document's `gamepad` Permissions Policy.

This event is not cancelable and does not bubble.

Examples
--------

To be informed when a gamepad is connected, you can add a handler to the window using `addEventListener()`, like this:

```js
window.addEventListener("gamepadconnected", (event) => {
  // All buttons and axes values can be accessed through
  const gamepad = event.gamepad;
});
```

Alternatively, you can use the `window.ongamepadconnected` event handler property to establish a handler for the `gamepadconnected` event:

```js
window.ongamepadconnected = (event) => {
  // All buttons and axes values can be accessed through
  const gamepad = event.gamepad;
};
```

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

| Specification |
| --- |
| Gamepad # event-gamepadconnected |

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

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

See also
--------

* gamepaddisconnected
* Using Gamepad API


Window: resizeTo() method - Web APIs

Window: resizeTo() method
=========================

 The **`Window.resizeTo()`** method dynamically resizes the
 window.

Syntax
------

```js
resizeTo(width, height)
```

### Parameters

`width`

 An integer representing the new `outerWidth` in
 pixels (including scroll bars, title bars, etc.).

`height`

 An integer value representing the new
 `outerHeight` in pixels (including scroll bars,
 title bars, etc.).

### Return value

None (`undefined`).

Examples
--------

 This function resizes the window so that it takes up one quarter of the available
 screen. See the `Screen.availWidth` and `Screen.availHeight`
 properties.

```js
function quarter() {
  window.resizeTo(window.screen.availWidth / 2, window.screen.availHeight / 2);
}
```

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

| Specification |
| --- |
| CSSOM View Module # dom-window-resizeto |

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

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

 Note: It's not possible to resize a window or tab that wasn't created by
 **`window.open()`**. It's also not possible to resize when the
 window has multiple tabs.

See also
--------

* `window.resizeBy()`


Window: find() method - Web APIs

Window: find() method
=====================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

**Note:** Support for `Window.find()` might change in future
 versions of Gecko. See Firefox bug 672395.

The **`Window.find()`** method finds a string in a window sequentially.

Syntax
------

```js
find(aString, aCaseSensitive, aBackwards, aWrapAround, aWholeWord, aSearchInFrames, aShowDialog)
```

### Parameters

`aString`

The text string for which to search.

`aCaseSensitive`

A boolean value. If `true`, specifies a case-sensitive search.

`aBackwards`

A boolean value. If `true`, specifies a backward search.

`aWrapAround`

A boolean value. If `true`, specifies a wrap around search.

`aWholeWord` Unimplemented

A boolean value. If `true`, specifies a whole word search. This is not implemented; see Firefox bug 481513.

`aSearchInFrames`

A boolean value. If `true`, specifies a search in frames.

### Return value

`true` if the string is found; otherwise, `false`.

Examples
--------

### JavaScript

```js
function findString(text) {
  document.querySelector("#output").textContent = `String found? ${window.find(
 text,
 )}`;
}
```

### HTML

```html
<p>Apples, Bananas, and Oranges.</p>
<button type="button" onClick='findString("Apples")'>Search for Apples</button>
<button type="button" onClick='findString("Bananas")'>
  Search for Bananas
</button>
<button type="button" onClick='findString("Orange")'>Search for Orange</button>

<p id="output"></p>
```

### Result

Notes
-----

 In some browsers, `Window.find()` selects (highlights) the found content on
 the site.

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

This is not part of any specification.

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

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


Window: matchMedia() method - Web APIs

Window: matchMedia() method
===========================

 The `Window` interface's **`matchMedia()`** method
 returns a new `MediaQueryList` object that can then be used to determine if
 the `document` matches the media query string,
 as well as to monitor the document to detect when it matches (or stops matching) that
 media query.

Syntax
------

```js
matchMedia(mediaQueryString)
```

### Parameters

`mediaQueryString`

A string specifying the media query to parse into a `MediaQueryList`.

### Return value

 A new `MediaQueryList` object for the media query. Use this object's
 properties and events to detect matches and to monitor for changes to those matches over
 time.

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

 You can use the returned media query to perform both instantaneous and event-driven
 checks to see if the document matches the media query.

 To perform a one-time, instantaneous check to see if the document matches the media
 query, look at the value of the `matches`
 property, which will be `true` if the document meets the media query's
 requirements.

 If you need to be kept aware of whether or not the document matches the media query at
 all times, you can instead watch for the `change` event to be delivered to the object. There's a good example of this
 in the article on `Window.devicePixelRatio`.

Examples
--------

 This example runs the media query `(max-width: 600px)` and displays the
 value of the resulting `MediaQueryList`'s `matches` property in a
 `<span>`; as a result, the output will say "true" if the viewport is less
 than or equal to 600 pixels wide, and will say "false" if the window is wider than that.

### JavaScript

```js
let mql = window.matchMedia("(max-width: 600px)");

document.querySelector(".mq-value").innerText = mql.matches;
```

 The JavaScript code passes the media query to match into `matchMedia()` to compile it, then sets the `<span>`'s
 `innerText` to the value of the results'
 `matches` property, so that it indicates whether or
 not the document matches the media query at the moment the page was loaded.

### HTML

```html
<span class="mq-value"></span>
```

A simple `<span>` to receive the output.
```

.mq-value {
  font:
    18px arial,
    sans-serif;
  font-weight: bold;
  color: #88f;
  padding: 0.4em;
  border: 1px solid #dde;
}
```

### Result

See Testing media queries programmatically for additional code examples.

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

| Specification |
| --- |
| CSSOM View Module # dom-window-matchmedia |

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
* `MediaQueryList`


Window: documentPictureInPicture property - Web APIs

Window: documentPictureInPicture property
=========================================

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

 The **`documentPictureInPicture`** read-only property of the
 `Window` interface returns a reference to the `DocumentPictureInPicture` object for the current document context.

Value
-----

A `DocumentPictureInPicture` object instance.

Examples
--------

```js
const videoPlayer = document.getElementById("player");

// ...

// Open a Picture-in-Picture window.
await window.documentPictureInPicture.requestWindow({
  width: videoPlayer.clientWidth,
  height: videoPlayer.clientHeight,
});

// ...
```

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

| Specification |
| --- |
| Document Picture-in-Picture Specification # dom-window-documentpictureinpicture |

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

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

See also
--------

* Document Picture-in-Picture API
* Using the Document Picture-in-Picture API


Window: credentialless property - Web APIs

Window: credentialless property
===============================

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

The **`window.credentialless`** read-only property returns a boolean that indicates whether the current document was loaded inside a credentialless `<iframe>`, meaning that it is loaded in a new, ephemeral context.

This context doesn't have access to the network, cookies, and storage data associated with its origin. It uses a new context local to the top-level document lifetime. In return, the `Cross-Origin-Embedder-Policy` (COEP) embedding rules can be lifted, so documents with COEP set can embed third-party documents that do not.

See IFrame credentialless for a deeper explanation.

Value
-----

A boolean. A value of `true` indicates that the document was loaded inside a credentialless `<iframe>`; `false` indicates that it was not.

Examples
--------

You can specify a credentialless `<iframe>` like so:

```html
<iframe
 src="https://en.wikipedia.org/wiki/Spectre\_(security\_vulnerability)"
 title="Spectre vulnerability Wikipedia page"
 width="960"
 height="600"
 credentialless></iframe>
```

In supporting browsers, if the document loaded in the `<iframe>` were to run the following line, it would return `true`:

```js
console.log(window.credentialless);
```

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

| Specification |
| --- |
| Iframe credentialless # dom-window-credentialless |

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

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


Window: moveBy() method - Web APIs

Window: moveBy() method
=======================

 The **`moveBy()`** method of the `Window`
 interface moves the current window by a specified amount.

**Note:** This function moves the window relative to its current
 location. In contrast, `window.moveTo()` moves the window to an absolute
 location.

Syntax
------

```js
moveBy(deltaX, deltaY)
```

### Parameters

* `deltaX` is the amount of pixels to move the window horizontally.
 Positive values are to the right, while negative values are to the left.
* `deltaY` is the amount of pixels to move the window vertically. Positive
 values are down, while negative values are up.
### Return value

None (`undefined`).

Examples
--------

This example moves the window 10 pixels to the right and 10 pixels up.

```js
function budge() {
  moveBy(10, -10);
}
```

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

| Specification |
| --- |
| CSSOM View Module # dom-window-moveby |

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

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

As of Firefox 7, websites can no longer move a browser window in the following cases:

1. You can't move a window or tab that wasn't created by `Window.open()`.
2. You can't move a window or tab when it's in a window with more than one tab.
See also
--------

* `Window.moveTo()`


Window: showOpenFilePicker() method - Web APIs

Window: showOpenFilePicker() method
===================================

**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 **`showOpenFilePicker()`** method of the
 `Window` interface shows a file picker that allows a user to select a file
 or multiple files and returns a handle for the file(s).

Syntax
------

```js
showOpenFilePicker()
```

### Parameters

`options` Optional

An object containing options, which are as follows:

`excludeAcceptAllOption` Optional

 A boolean value that defaults to
 `false`. By default the picker should include an option to not apply
 any file type filters (instigated with the type option below). Setting this option
 to `true` means that option is *not* available.

`id` Optional

 By specifying an ID, the browser can remember different directories for different
 IDs. If the same ID is used for another picker, the picker opens in the same
 directory.

`multiple` Optional

 A boolean value that defaults to `false`. When
 set to `true` multiple files may be selected.

`startIn` Optional

 A `FileSystemHandle` or a well known directory (`"desktop"`, `"documents"`,
 `"downloads"`, `"music"`, `"pictures"`, or `"videos"`) to open the dialog in.

`types` Optional

 An `Array` of allowed file types to pick. Each
 item is an object with the following options:

`description` Optional

An optional description of the category of files types allowed. Defaults to an empty string.

`accept`

 An `Object` with the keys set to the MIME type and the values an `Array` of file extensions (see below
 for an example).

### Return value

A `Promise` whose fulfillment handler receives an `Array` of `FileSystemFileHandle` objects.

### Exceptions

`AbortError` `DOMException`

 Thrown if the user dismisses the prompt without making a selection, or
 if the user agent deems any selected files too sensitive or dangerous.

`SecurityError` `DOMException`

Thrown if the call was blocked by the same-origin policy or it was not called via a user interaction such as a button press.

`TypeError`

Thrown if accept types can't be processed, which may happen if:

* Any key string of the `accept` options of any item in `types` options can't parse a valid MIME type.
* Any value string(s) of the `accept` options of any item in `types` options is invalid, for example, if it does not start with `.` and if end with `.`, or if it contains any invalid code points and its length is more than 16.
* The `types` options is empty and the `excludeAcceptAllOption` options is `true`.

Security
--------

Transient user activation is required. The user has to interact with the page or a UI element in order for this feature to work.

Examples
--------

 Here we set the options object for passing into the method. We'll allow a selection of
 image file types, with no option to allow for all files types, or multiple file
 selection.

```js
const pickerOpts = {
  types: [
    {
      description: "Images",
      accept: {
        "image/\*": [".png", ".gif", ".jpeg", ".jpg"],
      },
    },
  ],
  excludeAcceptAllOption: true,
  multiple: false,
};
```

 Next we can create an asynchronous function which show the file picker and return the
 selected file.

```js
// create a reference for our file handle
let fileHandle;

async function getFile() {
  // open file picker, destructure the one element returned array
  [fileHandle] = await window.showOpenFilePicker(pickerOpts);

  // run code with our fileHandle
}
```

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

| Specification |
| --- |
| File System Access # api-showopenfilepicker |

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

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

See also
--------

* File System API
* The File System Access API: simplifying access to local files


Window: speechSynthesis property - Web APIs

Window: speechSynthesis property
================================

The `speechSynthesis` read-only property of the Window object returns a `SpeechSynthesis` object, which is the entry point into using Web Speech API speech synthesis functionality.

Value
-----

A `SpeechSynthesis` object.

Examples
--------

 In our basic Speech synthesizer demo, we first grab a reference to the SpeechSynthesis controller using `window.speechSynthesis`.
 After defining some necessary variables, we retrieve a list of the voices available using `SpeechSynthesis.getVoices()` and populate a select menu with them so the user can choose what voice they want.

Inside the `inputForm.onsubmit` handler, we stop the form submitting with preventDefault(), create a new `SpeechSynthesisUtterance` instance containing the text from the text `<input>`, set the utterance's voice to the voice selected in the `<select>` element, and start the utterance speaking via the `SpeechSynthesis.speak()` method.

```js
const synth = window.speechSynthesis;

const inputForm = document.querySelector("form");
const inputTxt = document.querySelector("input");
const voiceSelect = document.querySelector("select");

function populateVoiceList() {
  voices = synth.getVoices();

  for (const voice of voices) {
    const option = document.createElement("option");
    option.textContent = `${voice.name} (${voice.lang})`;

    if (voice.default) {
      option.textContent += " — DEFAULT";
    }

    option.setAttribute("data-lang", voice.lang);
    option.setAttribute("data-name", voice.name);
    voiceSelect.appendChild(option);
  }
}

populateVoiceList();
if (speechSynthesis.onvoiceschanged !== undefined) {
  speechSynthesis.onvoiceschanged = populateVoiceList;
}

inputForm.onsubmit = (event) => {
  event.preventDefault();

  const utterThis = new SpeechSynthesisUtterance(inputTxt.value);
  const selectedOption =
    voiceSelect.selectedOptions[0].getAttribute("data-name");
  utterThis.voice = voices.find((v) => v.name === selectedOption);
  synth.speak(utterThis);
  inputTxt.blur();
};
```

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

| Specification |
| --- |
| Web Speech API # tts-section |

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

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

See also
--------

* Web Speech API


Window: webkitConvertPointFromPageToNode() method - Web APIs

Window: webkitConvertPointFromPageToNode() method
=================================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 Given a `WebKitPoint` specified in the page's coordinate system, the
 `Window` method **`webkitConvertPointFromPageToNode()`**
 returns a `Point` object specifying the same location in the coordinate
 system of the specified DOM `Node`.

**Warning:** Please review the Browser compatibility section before using this method,
 as it's not widely supported (nor is the `WebKitPoint` object it uses).

Syntax
------

```js
convertPointFromPageToNode(node, pagePoint)
```

### Parameters

`node`

The `Node` into whose coordinate system the point is to be converted.

`pagePoint`

 A `WebKitPoint` object specifying a point in the coordinate system of the
 page, which is to be converted into the node's coordinate system.

### Return value

 A `Point` object describing the specified location in the node's coordinate
 system.

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

 This method was specified in the defunct 20 March 2009 Working Draft of CSS 2D Transforms Module Level 3. It is not present in the
 current CSS Transforms Module Level 1 Working Draft.

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

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

See also
--------

* `Window.webkitConvertPointFromNodeToPage`
* Mozilla implementation bug: Firefox bug 850808
* `webkitConvertPointFromPageToNode` documentation at IE Dev Center


Window: screenLeft property - Web APIs

Window: screenLeft property
===========================

 The **`Window.screenLeft`** read-only property returns the
 horizontal distance, in CSS pixels, from the left border of the user's browser viewport
 to the left side of the screen.

**Note:** `screenLeft` is an alias of the older
 `Window.screenX` property. `screenLeft` was originally
 supported only in IE but was introduced everywhere due to popularity.

Value
-----

 A number equal to the number of CSS pixels from the left edge of the browser viewport
 to the left edge of the screen.

Examples
--------

 In our screenleft-screentop
 example, you'll see a canvas onto which has been drawn a circle. In this example we are
 using `screenLeft`/`screenTop` plus
 `Window.requestAnimationFrame()` to constantly redraw the circle in the
 same physical position on the screen, even if the window position is moved.

```js
initialLeft = window.screenLeft + canvasElem.offsetLeft;
initialTop = window.screenTop + canvasElem.offsetTop;

function positionElem() {
  let newLeft = window.screenLeft + canvasElem.offsetLeft;
  let newTop = window.screenTop + canvasElem.offsetTop;

  let leftUpdate = initialLeft - newLeft;
  let topUpdate = initialTop - newTop;

  ctx.fillStyle = "rgb(0 0 0)";
  ctx.fillRect(0, 0, width, height);
  ctx.fillStyle = "rgb(0 0 255)";
  ctx.beginPath();
  ctx.arc(
    leftUpdate + width / 2,
    topUpdate + height / 2 + 35,
    50,
    degToRad(0),
    degToRad(360),
    false,
  );
  ctx.fill();

  pElem.textContent = `Window.screenLeft: ${window.screenLeft}, Window.screenTop: ${window.screenTop}`;

  window.requestAnimationFrame(positionElem);
}

window.requestAnimationFrame(positionElem);
```

 Also in the code we include a snippet that detects whether `screenLeft` is
 supported, and if not, polyfills in `screenLeft`/`screenTop` using
 `Window.screenX`/`Window.screenY`.

```js
if (!window.screenLeft) {
  window.screenLeft = window.screenX;
  window.screenTop = window.screenY;
}
```

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

| Specification |
| --- |
| CSSOM View Module # dom-window-screenleft |

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

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

See also
--------

* `window.screenTop`
* `Window.screenX`


Window: window property - Web APIs

Window: window property
=======================

The **`window`** property of a `Window` object points to the window object itself.

Thus, the following expressions all return the same window object:

```js
window.window;
window.window.window;
window.window.window.window;
// …
```

In web pages, the window object is also a *global object*. This means:

1. Global variables of your script are, in fact, properties of `window`:

```js
var global = { data: 0 };
alert(global === window.global); // displays "true"
```

2. You can access the built-in properties of the window object without having to prefix them with `window.`:

```js
setTimeout("alert('Hi!')", 50); // equivalent to using window.setTimeout().
alert(window === window.window); // displays "true"
```

The point of having the `window` property refer to the object itself, was likely to make it easy to refer to the global object. Otherwise, you'd have to do a manual `let window = this;` assignment at the top of your script.

Another reason, is that without this property you wouldn't be able to write, for example, "`window.open('https://google.com/')`". You'd have to use `open('https://google.com/')` instead.

Yet another reason to use this property, is for libraries which wish to offer OOP-versions, and non-OOP versions (especially JavaScript modules). For example, if we refer to "this.window.location.href", a JavaScript module could define a property called "window" inside of a class it defined (since no global "window" variable exists for it by default) which could be created after passing in a window object to the module class' constructor. Thus, "this.window" inside of its functions would refer to that window object. In the non-namespaced version, "this.window" would refer back to "window", and also be able to readily get the document location. Another advantage, is that the objects of such a class (even if the class were defined outside of a module) could change their reference to the window at will, they would not be able to do this if they had hard-coded a reference to "window". The default in the class could still be set as the current window object.

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

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

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

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


Window: captureEvents() method - Web APIs

Window: captureEvents() method
==============================

**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 **`Window.captureEvents()`** method does nothing.

**Note:** This is an method long removed from the specification. It is kept in browsers to prevent code breakage but does nothing.

Syntax
------

```js
captureEvents()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| HTML Standard # dom-window-captureevents |

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

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


Window: mozInnerScreenY property - Web APIs

Window: mozInnerScreenY property
================================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The `mozInnerScreenY` property of the `Window` interface returns the Y coordinate of the top-left corner of the window's viewport, in screen
 coordinates.

**Note:** This coordinate is reported in CSS pixels, not in hardware pixels.

Value
-----

The `window.mozInnerScreenY` property is a floating point, read-only value; it has no default value.

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

This feature is not part of any current specification. It is not on track to become a standard.

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

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

See also
--------

* `window.mozInnerScreenX`


Window: deviceorientationabsolute event - Web APIs

Window: deviceorientationabsolute event
=======================================

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

The **`deviceorientationabsolute`** event is fired when absolute device orientation changes.

This event is not cancelable and does not bubble.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("deviceorientationabsolute", (event) => {});

ondeviceorientationabsolute = (event) => {};
```

Event type
----------

A `DeviceOrientationEvent`. Inherits from `Event`.

Event

DeviceOrientationEventEvent properties
----------------

`DeviceOrientationEvent.absolute` Read only

A boolean that indicates whether the device is providing orientation data absolutely.

`DeviceOrientationEvent.alpha` Read only

A number representing the motion of the device around the z axis, expressed in degrees with values ranging from 0 (inclusive) to 360 (exclusive).

`DeviceOrientationEvent.beta` Read only

A number representing the motion of the device around the x axis, expressed in degrees with values ranging from -180 (inclusive) to 180 (exclusive). This represents a front to back motion of the device.

`DeviceOrientationEvent.gamma` Read only

A number representing the motion of the device around the y axis, expressed in degrees with values ranging from -90 (inclusive) to 90 (exclusive). This represents a left to right motion of the device.

`DeviceOrientationEvent.webkitCompassHeading`
Non-standard
 Read only

A number represents the difference between the motion of the device around the z axis of the world system and the direction of north, expressed in degrees with values ranging from 0 to 360.

`DeviceOrientationEvent.webkitCompassAccuracy`
Non-standard
 Read only

The accuracy of the compass given as a positive or negative deviation. It's usually 10.

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

| Specification |
| --- |
| DeviceOrientation Event Specification # dom-window-ondeviceorientationabsolute |

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

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

See also
--------

* `devicemotion` event
* `deviceorientation` event
* Detecting device orientation


Window: scrollByPages() method - Web APIs

Window: scrollByPages() method
==============================

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

 The **`Window.scrollByPages()`** method scrolls the current
 document by the specified number of pages.

Syntax
------

```js
scrollByPages(pages)
```

### Parameters

* `pages` is the number of pages to scroll. It may be a positive or
 negative integer.
### Return value

None (`undefined`).

Examples
--------

```js
// scroll down the document by 1 page
window.scrollByPages(1);

// scroll up the document by 1 page
window.scrollByPages(-1);
```

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

DOM Level 0. Not part of specification.

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

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

See also
--------

* `window.scroll()`
* `window.scrollBy()`
* `window.scrollByLines()`
* `window.scrollTo()`


Sensor: activated property - Web APIs

Sensor: activated property
==========================

 The **`activated`** read-only property
 of the `Sensor` interface returns a boolean value indicating
 whether the sensor is active.

 Because `Sensor` is a base class, `activated` may only be read
 from one of its derived classes.

Value
-----

A boolean value.

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

| Specification |
| --- |
| Generic Sensor API # sensor-activated |

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

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


Sensor: start() method - Web APIs

Sensor: start() method
======================

 The **`start`** method activates one
 of the sensors based on `Sensor`.

Syntax
------

```js
start()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| Generic Sensor API # sensor-start |

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

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


Sensor: hasReading property - Web APIs

Sensor: hasReading property
===========================

 The **`hasReading`** read-only
 property of the `Sensor` interface returns a boolean value
 indicating whether the sensor has a reading.

 Because `Sensor` is a base class, `hasReading` may only be read
 from one of its derived classes.

Value
-----

A boolean value.

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

| Specification |
| --- |
| Generic Sensor API # sensor-has-reading |

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

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


Sensor: reading event - Web APIs

Sensor: reading event
=====================

The **`reading`** event is fired when a new reading is available on a sensor.

 The `Sensor` interface is a base class, `onreading` and the `reading` event may only be used
 on one of the derived classes.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("reading", (event) => {});

onreading = (event) => {};
```

Event type
----------

A generic `Event` with no added properties.

Examples
--------

### Reading acceleration

This example adds an event listener to read acceleration values of an `Accelerometer`. It reads sixty times a second.

```js
const acl = new Accelerometer({ frequency: 60 });
acl.addEventListener("reading", () => {
  console.log(`Acceleration along the X-axis ${acl.x}`);
  console.log(`Acceleration along the Y-axis ${acl.y}`);
  console.log(`Acceleration along the Z-axis ${acl.z}`);
});
acl.start();
```

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

| Specification |
| --- |
| Generic Sensor API # sensor-onreading |

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

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

See also
--------

* Sensor `activate` event
* Sensor `error` event


Sensor: timestamp property - Web APIs

Sensor: timestamp property
==========================

 The **`timestamp`** read-only property
 of the `Sensor` interface returns the timestamp of the latest sensor
 reading.

 Because `Sensor` is a base class, `timestamp` may only be read
 from one of its derived classes.

Value
-----

A `DOMHighResTimeStamp`.

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

| Specification |
| --- |
| Generic Sensor API # sensor-timestamp |

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

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


Sensor: stop() method - Web APIs

Sensor: stop() method
=====================

 The **`stop`** method of the
 `Sensor` interface deactivates the current sensor.

Syntax
------

```js
stop()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
// TBD
```

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

| Specification |
| --- |
| Generic Sensor API # sensor-stop |

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

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


Sensor: activate event - Web APIs

Sensor: activate event
======================

The **`activate`** event is fired when a sensor becomes activated. It means that it will start obtaining readings.

 The `Sensor` interface is a base class, `onactivate` and the `activate` event may only be used
 on one of the derived classes.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("activate", (event) => {});

onactivate = (event) => {};
```

Event type
----------

A generic `Event` with no added properties.

Examples
--------

### Log when an accelerometer is ready to measure

This example adds an event listener to log the activation of an `Accelerometer`.

```js
const acl = new Accelerometer({ frequency: 60 });
acl.addEventListener("activate", () => console.log("Ready to measure."));
acl.start();
```

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

| Specification |
| --- |
| Generic Sensor API # sensor-onactivate |

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

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

See also
--------

* Sensor `error` event
* Sensor `reading` event


Sensor: error event - Web APIs

Sensor: error event
===================

The **`error`** event is fired when an exception occurs on a sensor.

 The `Sensor` interface is a base class, `onerror` and the `error` event may only be used
 on one of the derived classes.

After this event has occurred, the `Sensor` object becomes idle. If the sensor was reading values, it will stop until it restarts.

Syntax
------

Use the event name in methods like `addEventListener()`, or set an event handler property.

```js
addEventListener("error", (event) => {});

onerror = (event) => {};
```

Event type
----------

A `SensorErrorEvent`. Inherits from `Event`.

Event

SensorErrorEventEvent properties
----------------

*In addition to the properties listed below, properties from the parent interface, `Event`, are available.*

`error` Read only

Returns the `DOMException` that has been thrown.

Examples
--------

### Log accelerometer exceptions

This example adds an event listener to log errors occurred on an `Accelerometer`.

```js
const acl = new Accelerometer({ frequency: 60 });
acl.addEventListener("error", (error) => console.log(`Error: ${error.name}`));
acl.start();
```

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

| Specification |
| --- |
| Generic Sensor API # sensor-onerror |

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

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

See also
--------

* Sensor `activate` event
* Sensor `reading` event


VRFrameData: leftProjectionMatrix property - Web APIs

VRFrameData: leftProjectionMatrix property
==========================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`leftProjectionMatrix`** read-only property of the `VRFrameData` interface returns a `Float32Array` representing a 4x4 matrix that describes the projection to be used for the left eye's rendering.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

This value may be passed directly to WebGL's `uniformMatrix4fv` function.

**Warning:** It is highly recommended that applications use this matrix without modification. Failure to use this projection matrix when rendering may cause the presented frame to be distorted or badly aligned, resulting in varying degrees of user discomfort.

Value
-----

A `Float32Array` object.

Examples
--------

See `VRDisplay.getFrameData()` for example code.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRFrameData: timestamp property - Web APIs

VRFrameData: timestamp property
===============================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`timestamp`** read-only property of the `VRFrameData` interface returns a constantly increasing timestamp value representing the time a frame update occurred.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Timestamps are useful for determining if position state data has been updated from the hardware. Since values are monotonically increasing, they can be compared to determine the ordering of updates — newer values will always be greater than or equal to older values.

The timestamp starts at 0 the first time `VRDisplay.getFrameData()` is invoked for a given `VRDisplay`.

Value
-----

A `DOMHighResTimeStamp` object.

Examples
--------

```js
const frameData = new VRFrameData();
let vrDisplay;

navigator.getVRDisplays().then((displays) => {
  vrDisplay = displays[0];
  console.log("Display found");
  // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
  btn.addEventListener("click", () => {
    vrDisplay.requestPresent([{ source: canvas }]).then(() => {
      drawVRScene();
    });
  });
});

// WebVR: Draw the scene for the WebVR display.
function drawVRScene() {
  // WebVR: Request the next frame of the animation
  vrSceneFrame = vrDisplay.requestAnimationFrame(drawVRScene);

  // Populate frameData with the data of the next frame to display
  vrDisplay.getFrameData(frameData);

  // grab the current timestamp on each run of the rendering loop
  // and do something with it
  framedata.timestamp;

  // …

  // WebVR: Indicates that we are ready to present the rendered frame to the VR display
  vrDisplay.submitFrame();
}
```

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRFrameData: leftViewMatrix property - Web APIs

VRFrameData: leftViewMatrix property
====================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`leftViewMatrix`** read-only property of the `VRFrameData` interface returns a `Float32Array` representing a 4x4 matrix that describes the view transform to be used for the left eye's rendering.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

This value may be passed directly to WebGL's `uniformMatrix4fv` function.

**Warning:** It is highly recommended that applications use this matrix when rendering.

Value
-----

A `Float32Array` object.

Examples
--------

See `VRDisplay.getFrameData()` for example code.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRFrameData: rightViewMatrix property - Web APIs

VRFrameData: rightViewMatrix property
=====================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`rightViewMatrix`** read-only property of the `VRFrameData` interface returns a `Float32Array` representing a 4x4 matrix that describes the view transform to be used for the right eye's rendering.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

This value may be passed directly to WebGL's `uniformMatrix4fv` function.

**Warning:** It is highly recommended that applications use this matrix when rendering.

Value
-----

A `Float32Array` object.

Examples
--------

See `VRDisplay.getFrameData()` for example code.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRFrameData: VRFrameData() constructor - Web APIs

VRFrameData: VRFrameData() constructor
======================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`VRFrameData()`** constructor creates a `VRFrameData` object instance.

**Note:** This constructor was part of the old WebVR API. It has been superseded by the WebXR Device API.

Syntax
------

```js
new VRFrameData()
```

### Parameters

None.

Examples
--------

See `VRDisplay.getFrameData()` for example code.

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

This constructor was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRFrameData: pose property - Web APIs

VRFrameData: pose property
==========================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`pose`** read-only property of the `VRFrameData` interface returns the `VRPose` of the `VRDisplay` at the current `VRFrameData.timestamp`.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

Value
-----

A `VRPose` object.

Examples
--------

See `VRDisplay.getFrameData()` for example code.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


VRFrameData: rightProjectionMatrix property - Web APIs

VRFrameData: rightProjectionMatrix property
===========================================

**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.

**Non-standard:** This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.

The **`rightProjectionMatrix`** read-only property of the `VRFrameData` interface returns a `Float32Array` representing a 4x4 matrix that describes the projection to be used for the right eye's rendering.

**Note:** This property was part of the old WebVR API. It has been superseded by the WebXR Device API.

This value may be passed directly to WebGL's `uniformMatrix4fv` function.

**Warning:** It is highly recommended that applications use this matrix without modification. Failure to use this projection matrix when rendering may cause the presented frame to be distorted or badly aligned, resulting in varying degrees of user discomfort.

Value
-----

A `Float32Array` object.

Examples
--------

See `VRDisplay.getFrameData()` for example code.

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

This property was part of the old WebVR API that has been superseded by the WebXR Device API. It is no longer on track to becoming a standard.

Until all browsers have implemented the new WebXR APIs, it is recommended to rely on frameworks, like A-Frame, Babylon.js, or Three.js, or a polyfill, to develop WebXR applications that will work across all browsers [1].

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

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

See also
--------

* WebVR API


OffscreenCanvas: convertToBlob() method - Web APIs

OffscreenCanvas: convertToBlob() method
=======================================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`OffscreenCanvas.convertToBlob()`** method creates a `Blob` object representing the image contained in the canvas.

 The desired file format and image quality may be specified.
 If the file format is not specified, or if the given format is not supported, then the data will be exported as `image/png`.
 Browsers are required to support `image/png`; many will support additional formats including `image/jpeg` and `image/webp`.

The created image will have a resolution of 96dpi for file formats that support encoding resolution metadata.

Syntax
------

```js
convertToBlob()
convertToBlob(options)
```

### Parameters

`options` Optional

An object with the following properties:

`type`

 A string indicating the image format.
 The default type is `image/png`; this image format will be also used if the specified type is not supported.

`quality`

 A `Number` between `0` and `1` indicating the image quality to be used when creating images using file formats that support lossy compression (such as `image/jpeg` or `image/webp`).
 A user agent will use its default quality value if this option is not specified, or if the number is outside the allowed range.

### Return value

A `Promise` returning a `Blob` object representing the image contained in the canvas.

### Exceptions

The promise may be rejected with the following exceptions:

`InvalidStateError` `DOMException`

The `OffscreenCanvas` is not detached; in other words it still associated with the DOM and not the current worker.

`SecurityError` `DOMException`

The canvas context mode is 2d and the bitmap is not origin-clean; at least some of its contents have or may have been loaded from a site other than the one from which the document itself was loaded.

`IndexSizeError` `DOMException`

The canvas bitmap has no pixels (either the horizontal or vertical dimension is zero).

`EncodingError` `DOMException`

The blob could not be created due to an encoding error.

Examples
--------

```js
const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");

// Perform some drawing using the gl context

offscreen.convertToBlob().then((blob) => console.log(blob));
// Blob { size: 334, type: "image/png" }
```

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

| Specification |
| --- |
| HTML Standard # dom-offscreencanvas-converttoblob-dev |

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

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

See also
--------

* The interface defining this method, `OffscreenCanvas`.


OffscreenCanvas: getContext() method - Web APIs

OffscreenCanvas: getContext() method
====================================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`OffscreenCanvas.getContext()`** method returns a drawing context for an offscreen canvas, or `null` if the context identifier is not supported.

Syntax
------

```js
getContext(contextType, contextAttributes)
```

### Parameters

`contextType`

A string containing the context identifier defining the drawing context associated to the canvas. Possible values are:

`2d`

Creates a `OffscreenCanvasRenderingContext2D` object representing a two-dimensional rendering context.

`webgl`

 Creates a `WebGLRenderingContext` object representing a three-dimensional rendering context.
 This context is only available on browsers that implement WebGL version 1 (OpenGL ES 2.0).

`webgl2`

 Creates a `WebGL2RenderingContext` object representing a three-dimensional rendering context.
 This context is only available on browsers that implement WebGL version 2 (OpenGL ES 3.0).

`bitmaprenderer`

Creates a `ImageBitmapRenderingContext` which only provides functionality to replace the content of the canvas with a given `ImageBitmap`.

**Note:** The identifiers **`"experimental-webgl"`** or **`"experimental-webgl2"`** are also used in implementations of WebGL.
 These implementations have not reached test suite conformance, or the graphic drivers situation on the platform is not yet stable.
 The Khronos Group certifies WebGL implementations under certain conformance rules.

`contextAttributes`

You can use several context attributes when creating your rendering context, for example:

```js
offscreen.getContext("webgl", { antialias: false, depth: false });
```

2d context attributes:

`alpha`

Boolean that indicates if the canvas contains an alpha channel. If set to `false`, the browser now knows that the backdrop is always opaque, which can speed up drawing of transparent content and images then.

`willReadFrequently`
Non-standard
 (Firefox only)

 Boolean that indicates whether or not a lot of read-back operations are planned.
 This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling `getImageData()` frequently.
 This option is only available, if the flag `gfx.canvas.willReadFrequently.enable` is set to `true` (which, by default, is only the case for B2G/Firefox OS).

`storage`
Non-standard
 (Blink only)

String that indicates which storage is used ("persistent" by default).

WebGL context attributes:

`alpha`

Boolean that indicates if the canvas contains an alpha buffer.

`depth`

Boolean that indicates that the drawing buffer is requested to have a depth buffer of at least 16 bits.

`stencil`

Boolean that indicates that the drawing buffer is requested to have a stencil buffer of at least 8 bits.

`antialias`

Boolean that indicates whether or not to perform anti-aliasing if possible.

`premultipliedAlpha`

Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha.

`preserveDrawingBuffer`

If the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.

`failIfMajorPerformanceCaveat`

Boolean that indicates if a context will be created if the system performance is low.

### Return value

A rendering context which is either a

* `OffscreenCanvasRenderingContext2D` for `"2d"`,
* `WebGLRenderingContext` for `"webgl"` and `"experimental-webgl"`,
* `WebGL2RenderingContext` for `"webgl2"` and `"experimental-webgl2"`
Experimental
, or
* `ImageBitmapRenderingContext` for `"bitmaprenderer"`.

If the `contextType` doesn't match a possible drawing context, `null` is returned.

Examples
--------

```js
const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");

gl; // WebGLRenderingContext
gl.canvas; // OffscreenCanvas
```

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

| Specification |
| --- |
| HTML Standard # dom-offscreencanvas-getcontext-dev |

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

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

See also
--------

* The interface defining this method: `OffscreenCanvas`
* `HTMLCanvasElement.getContext()`
* Available rendering contexts: `CanvasRenderingContext2D`, `WebGLRenderingContext`, `WebGL2RenderingContext`, `ImageBitmapRenderingContext`, and `OffscreenCanvasRenderingContext2D`


OffscreenCanvas: width property - Web APIs

OffscreenCanvas: width property
===============================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`width`** property returns and sets the width of an `OffscreenCanvas` object.

Value
-----

Examples
--------

Creating a new offscreen canvas and returning or setting the width of the offscreen canvas:

```js
const offscreen = new OffscreenCanvas(256, 256);
offscreen.width; // 256
offscreen.width = 512;
```

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

| Specification |
| --- |
| HTML Standard # dom-offscreencanvas-width-dev |

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

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

See also
--------

* `OffscreenCanvas`, the interface this property belongs to.


OffscreenCanvas: OffscreenCanvas() constructor - Web APIs

OffscreenCanvas: OffscreenCanvas() constructor
==============================================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`OffscreenCanvas()`** constructor returns a newly instantiated `OffscreenCanvas` object.

Syntax
------

```js
new OffscreenCanvas(width, height)
```

### Parameters

`width`

The width of the offscreen canvas.

`height`

The height of the offscreen canvas.

Examples
--------

 This example creates a new offscreen canvas using the `OffscreenCanvas()` constructor.
 We then initialize a WebGL context on it using the `getContext()` method.

```js
const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");
```

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

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

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

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

See also
--------

* `OffscreenCanvas`, the interface this constructor belongs to


OffscreenCanvas: transferToImageBitmap() method - Web APIs

OffscreenCanvas: transferToImageBitmap() method
===============================================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`OffscreenCanvas.transferToImageBitmap()`** method creates an `ImageBitmap` object from the most recently rendered image of the `OffscreenCanvas`. The `OffscreenCanvas` allocates a new image for its subsequent rendering.

Syntax
------

```js
transferToImageBitmap()
```

### Parameters

None.

### Return value

A newly-allocated `ImageBitmap`.

This `ImageBitmap` references a potentially large graphics resource, and to ensure your web application remains robust, it is important to avoid allocating too many of these resources at any point in time. For this reason it is important to ensure that the `ImageBitmap` is either *consumed* or *closed*.

As described in the `OffscreenCanvas` examples, passing this `ImageBitmap` to `ImageBitmapRenderingContext.transferFromImageBitmap()` *consumes* the `ImageBitmap` object; it no longer references the underlying graphics resource, and can not be passed to any other web APIs.

If your goal is to pass the `ImageBitmap` to other web APIs which do not consume it - for example, `CanvasRenderingContext2D.drawImage()` - then you should *close* it when you're done with it by calling `ImageBitmap.close()`. Don't simply drop the JavaScript reference to the `ImageBitmap`; doing so will keep its graphics resource alive until the next time the garbage collector runs.

If you call `transferToImageBitmap()` and don't intend to pass it to `ImageBitmapRenderingContext.transferFromImageBitmap()`, consider whether you need to call `transferToImageBitmap()` at all. Many web APIs which accept `ImageBitmap` also accept `OffscreenCanvas` as an argument.

Examples
--------

```js
const offscreen = new OffscreenCanvas(256, 256);
const gl = offscreen.getContext("webgl");

// Perform some drawing using the gl context

offscreen.transferToImageBitmap();
// ImageBitmap { width: 256, height: 256 }

// Either:
// Pass this `ImageBitmap` to `ImageBitmapRenderingContext.transferFromImageBitmap`
// or:
// Use the `ImageBitmap` with other web APIs, and call `ImageBitmap.close()`!
```

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

| Specification |
| --- |
| HTML Standard # dom-offscreencanvas-transfertoimagebitmap-dev |

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

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

See also
--------

* The interface defining this method, `OffscreenCanvas`
* `ImageBitmapRenderingContext.transferFromImageBitmap`


OffscreenCanvas: height property - Web APIs

OffscreenCanvas: height property
================================

Baseline 2023
-------------

Newly availableSince March 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Learn more
* See full compatibility
* Report feedback
The **`height`** property returns and sets the height of an `OffscreenCanvas` object.

Value
-----

Examples
--------

Creating a new offscreen canvas and returning or setting the height of the offscreen canvas:

```js
const offscreen = new OffscreenCanvas(256, 256);
offscreen.height; // 256
offscreen.height = 512;
```

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

| Specification |
| --- |
| HTML Standard # dom-offscreencanvas-height-dev |

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

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

See also
--------

* `OffscreenCanvas`, the interface this property belongs to.


TimeRanges: length property - Web APIs

TimeRanges: length property
===========================

 The **`TimeRanges.length`** read-only property returns the
 number of ranges in the object.

Value
-----

A number.

Examples
--------

Given a video element with the ID "myVideo":

```js
const v = document.getElementById("myVideo");

const buf = v.buffered;

const numRanges = buf.length;

if (buf.length === 1) {
  // Only one range
  if (buf.start(0) === 0 && buf.end(0) === v.duration) {
    // The one range starts at the beginning and ends at
    // the end of the video, so the whole thing is loaded
  }
}
```

 This example looks at the time ranges and looks to see if the entire video has been
 loaded.

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

| Specification |
| --- |
| HTML Standard # dom-timeranges-length-dev |

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

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


TimeRanges: start() method - Web APIs

TimeRanges: start() method
==========================

The **`start()`** method of the `TimeRanges` interface returns the time offset at which a specified time range begins.

Syntax
------

```js
start(index)
```

### Parameters

`index`

The range number to return the starting time for.

### Return value

A number.

### Exceptions

`IndexSizeError` `DOMException`

 Thrown if the specified index doesn't correspond to an
 existing range.

Examples
--------

Given a video element with the ID "myVideo":

```js
const v = document.getElementById("myVideo");

const buf = v.buffered;

const numRanges = buf.length;

if (buf.length === 1) {
  // only one range
  if (buf.start(0) === 0 && buf.end(0) === v.duration) {
    // The one range starts at the beginning and ends at
    // the end of the video, so the whole thing is loaded
  }
}
```

 This example looks at the time ranges and looks to see if the entire video has been
 loaded.

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

| Specification |
| --- |
| HTML Standard # dom-timeranges-start-dev |

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

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


TimeRanges: end() method - Web APIs

TimeRanges: end() method
========================

The **`end()`** method of the `TimeRanges` interface returns the time offset at which a specified time range ends.

Syntax
------

```js
end(index)
```

### Parameters

`index`

The range number to return the ending time for.

### Return value

A number.

### Exceptions

`IndexSizeError` `DOMException`

Thrown if the specified index doesn't correspond to an existing range.

Examples
--------

Given a video element with the ID `"myVideo"`:

```js
const v = document.getElementById("myVideo");

const buf = v.buffered;

const numRanges = buf.length;

if (buf.length === 1) {
  // only one range
  if (buf.start(0) === 0 && buf.end(0) === v.duration) {
    // The one range starts at the beginning and ends at
    // the end of the video, so the whole thing is loaded
  }
}
```

 This example looks at the time ranges and looks to see if the entire video has been
 loaded.

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

| Specification |
| --- |
| HTML Standard # dom-timeranges-end-dev |

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

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