Window: showSaveFilePicker() method - Web APIs

Window: showSaveFilePicker() 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 **`showSaveFilePicker()`** method of the
 `Window` interface shows a file picker that allows a user to save a file.
 Either by selecting an existing file, or entering a name for a new file.

Syntax
------

```js
showSaveFilePicker()
```

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

`startIn` Optional

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

`suggestedName` Optional

A `String`. The suggested file name.

`types` Optional

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

`description` Optional

 An optional description of the category of files
 types allowed. Default to be 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 a `FileSystemFileHandle` object.

### Exceptions

`AbortError` `DOMException`

 Thrown if the user dismisses the file picker without selecting or inputting a file,
 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
--------

The following function shows a file picker, with text files highlighted for selection.

```js
async function getNewFileHandle() {
  const opts = {
    types: [
      {
        description: "Text file",
        accept: { "text/plain": [".txt"] },
      },
    ],
  };
  return await window.showSaveFilePicker(opts);
}
```

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

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

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: setResizable() method - Web APIs

Window: setResizable() 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.

This method does nothing; it is a no-op. It is solely kept for compatibility with Netscape 4.x.

Syntax
------

```js
setResizable()
```

### Return value

None (`undefined`).

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

Not part of any current specifications.

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

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


Window: history property - Web APIs

Window: history property
========================

The `Window.history` read-only property returns a reference to the `History` object, which provides an interface for manipulating the browser *session history* (pages visited in the tab or frame that the current page is loaded in).

See Manipulating the browser history for examples and details. In particular, that article explains security features of the `pushState()` and `replaceState()` methods that you should be aware of before using them.

Value
-----

A reference to the `History` object.

Examples
--------

```js
history.back(); // equivalent to clicking back button
history.go(-1); // equivalent to history.back();
```

Notes
-----

For top-level pages you can see the list of pages in the session history, accessible via the `History` object, in the browser's dropdowns next to the back and forward buttons.

For security reasons the `History` object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.

There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the `location.replace()` method, which replaces the current item of the session history with the provided URL.

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

| Specification |
| --- |
| HTML Standard # the-history-interface |

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

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


Window: scrollByLines() method - Web APIs

Window: scrollByLines() 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.scrollByLines()`** method scrolls the document by
 the specified number of lines.

Syntax
------

```js
scrollByLines(lines)
```

### Parameters

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

None (`undefined`).

Examples
--------

```html
<!-- Scroll up the document by 5 lines -->
<button id="scroll-up" onclick="scrollByLines(-5);">Up 5 lines</button>

<!-- Scroll down the document by 5 lines -->
<button id="scroll-down" onclick="scrollByLines(5);">Down 5 lines</button>
```

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.

See also
--------

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


Window: copy event - Web APIs

Window: copy event
==================

The **`copy`** event fires when the user initiates a copy action through the browser's user interface.

The original target for this event is the `Element` that was the intended target of the copy action. You can listen for this event on the `Window` interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: copy event.

Syntax
------

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

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

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

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

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventExamples
--------

```js
window.addEventListener("copy", (event) => {
  console.log("copy action initiated");
});
```

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

| Specification |
| --- |
| Clipboard API and events # clipboard-event-copy |
| HTML Standard # handler-oncopy |

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

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

See also
--------

* Related events: `cut`, `paste`
* This event on `Element` targets: `copy`
* This event on `Document` targets: `copy`


Window: offline event - Web APIs

Window: offline event
=====================

The **`offline`** event of the `Window` interface is fired when the browser has lost access to the network and the value of `Navigator.onLine` switches to `false`.

Syntax
------

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

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

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

A generic `Event`.

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

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

* `HTMLBodyElement`
* `HTMLFrameSetElement`
* `SVGSVGElement`
Examples
--------

```js
// addEventListener version
window.addEventListener("offline", (event) => {
  console.log("The network connection has been lost.");
});

// onoffline version
window.onoffline = (event) => {
  console.log("The network connection has been lost.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-offline |
| HTML Standard # handler-window-onoffline |

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

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

See also
--------

* `online`


Window: external property - Web APIs

Window: external 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.

The `external` property of the `Window` API returns an instance of the `External` interface, which was intended to contain functions related to adding external search providers to the browser. However, this is now deprecated, and the contained methods are now dummy functions that do nothing as per spec.

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

The `External` object has the following methods:

| Method | Description |
| --- | --- |
| `AddSearchProvider(*descriptionURL)*` |
 Dummy function; does nothing. See
 Autodiscovery of search plugins.
  |
| `IsSearchProviderInstalled()` | Dummy function; does nothing. |

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

| Specification |
| --- |
| HTML Standard # external |

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

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


Window: beforeinstallprompt event - Web APIs

Window: beforeinstallprompt event
=================================

The **`beforeinstallprompt`** event fires when the browser has detected that a website can be installed as a Progressive Web App.

There's no guaranteed time this event is fired, but it usually happens on page load.

The typical use for this event is when a web app wants to provide its own in-app UI inviting the user to install the app, rather than the generic one provided by the browser. This enables the app to provide more context about the app, explaining to the user why they might want to install it.

In this scenario, the handler for this event will:

* Keep a reference to the `BeforeInstallPromptEvent` object that's passed into it
* Reveal its in-app installation UI (this should be hidden by default, because not all browsers will support installation).

When the user uses the in-app installation UI to install the app, the in-app installation UI calls the `prompt()` method of the retained `BeforeInstallPromptEvent` object to show the installation prompt.

Syntax
------

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

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

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

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

A `BeforeInstallPromptEvent`. Inherits from `Event`.

Event

BeforeInstallPromptEventEvent properties
----------------

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

`BeforeInstallPromptEvent.platforms` Read only
Non-standard

Experimental

Returns an array of string items containing the platforms on which the event was dispatched. This is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to choose between a web version or an Android version.

`BeforeInstallPromptEvent.userChoice` Read only
Non-standard

Experimental

Returns a `Promise` that resolves to an object describing the user's choice when they were prompted to install the app.

Event methods
-------------

`BeforeInstallPromptEvent.prompt()`
Non-standard

Experimental

Show a prompt asking the user if they want to install the app. This method returns a `Promise` that resolves to an object describing the user's choice when they were prompted to install the app.

Examples
--------

In the following example an app provides its own install button, which has an `id` of `"install"`. Initially the button is hidden.

```html
<button id="install" hidden>Install</button>
```

The `beforeinstallprompt` handler:

* Cancels the event, which prevents the browser displaying its own install UI on some platforms
* Assigns the `BeforeInstallPromptEvent` object to a variable, so it can be used later
* Reveals the app's install button.

```js
let installPrompt = null;
const installButton = document.querySelector("#install");

window.addEventListener("beforeinstallprompt", (event) => {
  event.preventDefault();
  installPrompt = event;
  installButton.removeAttribute("hidden");
});
```

When clicked, the app's install button:

* Calls the `prompt()` method of the stored event object, to trigger the installation prompt.
* Resets its state by clearing the `installPrompt` variable and hiding itself again.

```js
installButton.addEventListener("click", async () => {
  if (!installPrompt) {
    return;
  }
  const result = await installPrompt.prompt();
  console.log(`Install prompt was: ${result.outcome}`);
  installPrompt = null;
  installButton.setAttribute("hidden", "");
});
```

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

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

See also
--------

* `BeforeInstallPromptEvent.prompt`
* `BeforeInstallPromptEvent`


Window: launchQueue property - Web APIs

Window: launchQueue property
============================

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

The `launchQueue` read-only property of the `Window` interface provides access to the `LaunchQueue` class, which allows custom launch navigation handling to be implemented in a progressive web app (PWA), with the handling context signified by the `launch_handler` manifest field `client_mode` value.

The custom launch navigation handling functionality is controlled by the properties of the `LaunchParams` object passed into the `LaunchQueue.setConsumer()` callback function.

Value
-----

A `LaunchQueue` object instance.

Examples
--------

```js
if ("launchQueue" in window) {
  window.launchQueue.setConsumer((launchParams) => {
    if (launchParams.targetURL) {
      const params = new URL(launchParams.targetURL).searchParams;

      // Assuming a music player app that gets a track passed to it to be played
      const track = params.get("track");
      if (track) {
        audio.src = track;
        title.textContent = new URL(track).pathname.substring(1);
        audio.play();
      }
    }
  });
}
```

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

| Specification |
| --- |
| Web App Launch Handler API # launchqueue-interface |

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

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

See also
--------

* Launch Handler API
* Launch Handler API: Control how your app is launched
* `Window.launchQueue`
* Musicr 2.0 demo app


Window: gamepaddisconnected event - Web APIs

Window: gamepaddisconnected event
=================================

The `gamepaddisconnected` event is fired when the browser detects that a gamepad has been disconnected.

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 disconnected, you can add a handler to the window using `addEventListener()`, like this:

```js
window.addEventListener("gamepaddisconnected", (event) => {
  console.log("Lost connection with the gamepad.");
});
```

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

```js
window.ongamepaddisconnected = (event) => {
  console.log("Lost connection with the gamepad.");
};
```

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

| Specification |
| --- |
| Gamepad # event-gamepaddisconnected |

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

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

See also
--------

* gamepadconnected
* Using Gamepad API


Window: deviceorientation event - Web APIs

Window: deviceorientation event
===============================

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

The **`deviceorientation`** event is fired when fresh data is available from an orientation sensor about the current orientation of the device as compared to the Earth coordinate frame. This data is gathered from a magnetometer inside the device.

See Orientation and motion data explained for details.

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("deviceorientation", (event) => {});

ondeviceorientation = (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, express 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 the 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 the 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 the 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.

Examples
--------

```js
if (window.DeviceOrientationEvent) {
  window.addEventListener(
    "deviceorientation",
    (event) => {
      const rotateDegrees = event.alpha; // alpha: rotation around z-axis
      const leftToRight = event.gamma; // gamma: left to right
      const frontToBack = event.beta; // beta: front back motion

      handleOrientationEvent(frontToBack, leftToRight, rotateDegrees);
    },
    true,
  );
}

const handleOrientationEvent = (frontToBack, leftToRight, rotateDegrees) => {
  // do something amazing
};
```

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

| Specification |
| --- |
| DeviceOrientation Event Specification # deviceorientation |
| DeviceOrientation Event Specification # ref-for-dom-window-ondeviceorientation |

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

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

See also
--------

* `devicemotion`
* Detecting device orientation
* Orientation and motion data explained


Window: popstate event - Web APIs

Window: popstate event
======================

The **`popstate`** event of the `Window` interface is fired when the active history entry changes while the user navigates the session history. It changes the current history entry to that of the last page the user visited or, if `history.pushState()` has been used to add a history entry to the history stack, that history entry is used instead.

Syntax
------

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

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

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

A `PopStateEvent`. Inherits from `Event`.

Event

PopStateEventEvent properties
----------------

`PopStateEvent.state` Read only

Returns a copy of the information that was provided to `pushState()` or `replaceState()`.

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

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

* `HTMLBodyElement`
* `HTMLFrameSetElement`
* `SVGSVGElement`
The history stack
-----------------

If the history entry being activated was created by a call to `history.pushState()` or was affected by a call to `history.replaceState()`, the `popstate` event's `state` property contains a copy of the history entry's state object.

These methods and their corresponding events can be used to add data to the history stack which can be used to reconstruct a dynamically generated page, or to otherwise alter the state of the content being presented while remaining on the same `Document`.

Note that just calling `history.pushState()` or `history.replaceState()` won't trigger a `popstate` event. The `popstate` event will be triggered by doing a browser action such as a click on the back or forward button (or calling `history.back()` or `history.forward()` in JavaScript).

Browsers tend to handle the `popstate` event differently on page load. Chrome (prior to v34) and Safari always emit a `popstate` event on page load, but Firefox doesn't.

**Note:** When writing functions that process `popstate` event it is important to take into account that properties like `window.location` will already reflect the state change (if it affected the current URL), but `document` might still not. If the goal is to catch the moment when the new document state is already fully in place, a zero-delay `setTimeout()` method call should be used to effectively put its inner *callback* function that does the processing at the end of the browser event loop: `window.onpopstate = () => setTimeout(doSomeThing, 0);`

When popstate is sent
---------------------

It's important to first understand that — to combat unwanted pop-ups — browsers may not fire the `popstate` event at all unless the page has been interacted with.

This section describes the steps that browsers follow in the cases where they *do* potentially fire the `popstate` event (that is, in the cases where the page has been interacted with).

When a navigation occurs — either due to the user triggering the browser's `Back` button or otherwise — the `popstate` event is near the end of the process to navigate to the new location. It happens after the new location has loaded (if needed), displayed, made visible, and so on — after the `pageshow` event is sent, but before the persisted user state information is restored and the `hashchange` event is sent.

To better understand when the `popstate` event is fired, consider this simplified sequence of events that occurs when the current history entry changes due to either the user navigating the site or the history being traversed programmatically. Here, the transition is changing the current history entry to one we'll refer to as **new-entry**. The current page's session history stack entry will be referred to as **current-entry**.

1. If **new-entry** doesn't currently contain an existing `Document`, fetch the content and create its `Document` before continuing. This will eventually send events such as `DOMContentLoaded` and `load` to the `Window` containing the document, but the steps below will continue to execute in the meantime.
2. If **current-entry**'s title wasn't set using one of the History API methods (`pushState()` or `replaceState()`), set the entry's title to the string returned by its `document.title` attribute.
3. If the browser has state information it wishes to store with the **current-entry** before navigating away from it, it then does so. The entry is now said to have "persisted user state." This information the browser might add to the history session entry may include, for instance, the document's scroll position, the values of form inputs, and other such data.
4. If **new-entry** has a different `Document` object than **current-entry**, the browsing context is updated so that its `document` property refers to the document referred to by **new-entry**, and the context's name is updated to match the context name of the now-current document.
5. Each form control within **new-entry**'s `Document` that has `autocomplete` configured with its autofill field name set to `off` is reset. See The HTML autocomplete attribute for more about the autocomplete field names and how autocomplete works.
6. If **new-entry**'s document is already fully loaded and ready—that is, its `readyState` is `complete`—and the document is not already visible, it's made visible and the `pageshow` event is fired at the document with the `PageTransitionEvent`'s `persisted` attribute set to `true`.
7. The document's `URL` is set to that of **new-entry**.
8. If the history traversal is being performed with replacement enabled, the entry immediately prior to the destination entry (taking into account the `delta` parameter on methods such as `go()`) is removed from the history stack.
9. If the **new-entry** doesn't have persisted user state and its URL's fragment is non-`null`, the document is scrolled to that fragment.
10. Next, **current-entry** is set to **new-entry**. The destination entry is now considered to be current.
11. If **new-entry** has serialized state information saved with it, that information is deserialized into `History.state`; otherwise, `state` is `null`.
12. If the value of `state` changed, the `popstate` event is sent to the document.
13. Any persisted user state is restored, if the browser chooses to do so.
14. If the original and new entries shared the same document, but had different fragments in their URLs, send the `hashchange` event to the window.

As you can see, the `popstate` event is nearly the last thing done in the process of navigating pages in this way.

Examples
--------

A page at `http://example.com/example.html` running the following code will generate logs as indicated:

```js
window.addEventListener("popstate", (event) => {
  console.log(
    `location: ${document.location}, state: ${JSON.stringify(event.state)}`,
  );
});
history.pushState({ page: 1 }, "title 1", "?page=1");
history.pushState({ page: 2 }, "title 2", "?page=2");
history.replaceState({ page: 3 }, "title 3", "?page=3");
history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null"
history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}"
```

The same example using the `onpopstate` event handler property:

```js
window.onpopstate = (event) => {
  console.log(
    `location: ${document.location}, state: ${JSON.stringify(event.state)}`,
  );
};
history.pushState({ page: 1 }, "title 1", "?page=1");
history.pushState({ page: 2 }, "title 2", "?page=2");
history.replaceState({ page: 3 }, "title 3", "?page=3");
history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null"
history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}"
```

Note that even though the original history entry (for `http://example.com/example.html`) has no state object associated with it, a `popstate` event is still fired when we activate that entry after the second call to `history.back()`.

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

| Specification |
| --- |
| HTML Standard # event-popstate |
| HTML Standard # handler-window-onpopstate |

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

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

See also
--------

* Manipulating the browser history (the History API)
* Window: `hashchange` event


Window: vrdisplaypresentchange event - Web APIs

Window: vrdisplaypresentchange 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.

**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 **`vrdisplaypresentchange`** event of the WebVR API is fired when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa.

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

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("vrdisplaypresentchange", (event) => {});

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

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

A `VRDisplayEvent`. Inherits from `Event`.

Event properties
----------------

*`VRDisplayEvent` also inherits properties from its parent object, `Event`.*

`VRDisplayEvent.display`
Deprecated
 Read only

The `VRDisplay` associated with this event.

`VRDisplayEvent.reason`
Deprecated
 Read only

A human-readable reason why the event was fired.

Examples
--------

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

```js
window.addEventListener("vrdisplaypresentchange", () => {
  info.textContent = vrDisplay.isPresenting
    ? "Display has started presenting."
    : "Display has stopped presenting.";
  reportDisplays();
});
```

Or use the `onvrdisplaypresentchange` event handler property:

```js
window.onvrdisplaypresentchange = () => {
  info.textContent = vrDisplay.isPresenting
    ? "Display has started presenting."
    : "Display has stopped presenting.";
  reportDisplays();
};
```

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

This event 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 Device API, 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


Window: sessionStorage property - Web APIs

Window: sessionStorage property
===============================

 The read-only **`sessionStorage`**
 property accesses a session `Storage` object for the current
 origin. `sessionStorage` is similar to
 `localStorage`; the difference is that while data
 in `localStorage` doesn't expire, data in `sessionStorage` is
 cleared when the *page session* ends.

* Whenever a document is loaded in a particular tab in the browser, a unique page
 session gets created and assigned to that particular tab. That page session is valid
 only for that particular tab.
* A page session lasts as long as the tab or the browser is open, and survives over
 page reloads and restores.
* **Opening a page in a new tab or window creates a new session with the value
of the top-level browsing context, which differs from how session cookies
work.**
* Opening multiple tabs/windows with the same URL creates `sessionStorage`
 for each tab/window.
* Duplicating a tab copies the tab's `sessionStorage` into the new
 tab.
* Closing a tab/window ends the session and clears objects in
 `sessionStorage`.

 Data stored in `sessionStorage` **is specific to the protocol of the
page**. In particular, data stored by a script on a site accessed with HTTP
 (e.g., http://example.com) is
 put in a different `sessionStorage` object from the same site accessed with
 HTTPS (e.g., https://example.com).

 The keys and the values are *always* in the UTF-16 string
 format, which uses two bytes per character. As with objects, integer keys are
 automatically converted to strings.

Value
-----

 A `Storage` object which can be used to access the current origin's
 session storage space.

### Exceptions

`SecurityError`

Thrown in one of the following cases:

* The origin is not a valid scheme/host/port tuple. This can happen if the origin uses the `file:` or `data:` schemes, for example.
* The request violates a policy decision. For example, the user has configured the browsers to prevent the page from persisting data.

Note that if the user blocks cookies, browsers will probably interpret this as an instruction to prevent the page from persisting data.

Examples
--------

### Basic usage

```js
// Save data to sessionStorage
sessionStorage.setItem("key", "value");

// Get saved data from sessionStorage
let data = sessionStorage.getItem("key");

// Remove saved data from sessionStorage
sessionStorage.removeItem("key");

// Remove all saved data from sessionStorage
sessionStorage.clear();
```

### Saving text between refreshes

 The following example autosaves the contents of a text field, and if the browser is
 refreshed, restores the text field content so that no writing is lost.

```js
// Get the text field that we're going to track
let field = document.getElementById("field");

// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if (sessionStorage.getItem("autosave")) {
  // Restore the contents of the text field
  field.value = sessionStorage.getItem("autosave");
}

// Listen for changes in the text field
field.addEventListener("change", () => {
  // And save the results into the session storage object
  sessionStorage.setItem("autosave", field.value);
});
```

**Note:** Please refer to the Using the Web Storage API article for a full example.

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

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

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

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

See also
--------

* Using the Web Storage API
* `Window.localStorage`


Window: confirm() method - Web APIs

Window: confirm() method
========================

`window.confirm()` instructs the browser to display a dialog with an optional message, and to wait until the user either confirms or cancels the dialog.

Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to confirm or cancel the dialog.

Syntax
------

```js
confirm(message)
```

### Parameters

`message`

A string you want to display in the confirmation dialog.

### Return value

 A boolean indicating whether OK (`true`) or Cancel (`false`) was
 selected. If a browser is ignoring in-page dialogs, then the returned value is always
 `false`.

Examples
--------

```js
if (window.confirm("Do you really want to leave?")) {
  window.open("exit.html", "Thanks for Visiting!");
}
```

Produces:

![Firefox confirm](/en-US/docs/Web/API/Window/confirm/firefox_confirm_dialog.png)

Notes
-----

 Dialog boxes are modal windows — they
 prevent the user from accessing the rest of the program's interface until the dialog box
 is closed. For this reason, you should not overuse any function that creates a dialog
 box (or modal window). Regardless, there are good reasons to avoid using dialog boxes for confirmation.

Alternatively `<dialog>` element can be used for confirmations.

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

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

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

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

See also
--------

* `<dialog>` element
* `window.alert()`
* `window.prompt()`


Window: innerWidth property - Web APIs

Window: innerWidth property
===========================

The read-only `Window` property **`innerWidth`** returns the interior width of the window in pixels (that is, the width of the window's layout viewport). That includes the width of the vertical scroll bar, if one is present.

Similarly, the interior height of the window (that is, the height of the layout viewport) can be obtained using the `innerHeight` property. That measurement also accounts for the height of the horizontal scroll bar, if it is visible.

Value
-----

 An integer value indicating the width of the window's layout viewport in pixels. This
 property is read-only, and has no default value.

 To change the window's width, use one of the `Window` methods for resizing
 windows, such as `resizeBy()` or
 `resizeTo()`.

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

 If you need to obtain the width of the window minus the scrollbar and borders, use the
 root `<html>` element's `clientWidth`
 property instead.

 The `innerWidth` property is available on any window or object that behaves
 like a window, such as a frame or tab.

Examples
--------

```js
// This will log the width of the viewport
console.log(window.innerWidth);

// This will log the width of the frame viewport within a frameset
console.log(self.innerWidth);

// This will log the width of the viewport of the closest frameset
console.log(parent.innerWidth);

// This will log the width of the viewport of the outermost frameset
console.log(top.innerWidth);
```

Demo
----

### HTML

```html
<p>Resize the browser window to fire the <code>resize</code> event.</p>
<p>Window height: <span id="height"></span></p>
<p>Window width: <span id="width"></span></p>
```

### JavaScript

```js
const heightOutput = document.querySelector("#height");
const widthOutput = document.querySelector("#width");

function updateSize() {
  heightOutput.textContent = window.innerHeight;
  widthOutput.textContent = window.innerWidth;
}

updateSize();
window.addEventListener("resize", updateSize);
```

### Result

You can also view the results of the demo code in a separate page.

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

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

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

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

See also
--------

* `window.outerWidth`
* `window.innerHeight`
* `window.outerHeight`


Window: showModalDialog() method - Web APIs

Window: showModalDialog() 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.

**Warning:** This feature has been removed. Please fix your websites and applications.

This method was removed in Chrome 43 and Firefox 56.

 The **`Window.showModalDialog()`**
 created and displayed a modal dialog box containing a specified HTML document.

Syntax
------

```js
showModalDialog(uri)
showModalDialog(uri, arguments)
showModalDialog(uri, arguments, options)
```

### Parameters

`uri`

Is the URL of the document to display in the dialog.

`arguments` Optional

 Values passed to the dialog.
 property.

`options` Optional

 A string specifying window ornamentation for the
 dialog, using one or more semicolon delimited values:

| Syntax | Description |
| --- | --- |
| `center: {on | off | yes | no | 1 | 0 }` |
 If `on`, `yes`, or `1`, the dialog
 window is centered on the desktop; otherwise it's hidden. Default is
 `yes`.
  |
| `dialogheight: *height*` | The height of the dialog box in pixels. |
| `dialogleft: *left*` | Distance of the dialog box from the left edge of the desktop. |
| `dialogwidth: *width*` | The width of the dialog box in pixels. |
| `dialogtop: *top*` | Distance of the dialog box from the top edge of the desktop. |
| `resizable: {on | off | yes | no | 1 | 0 }` |
 If this argument's value is `on`, `yes`, or 1, the
 dialog window can be resized by the user; otherwise its size is fixed.
 The default value is `no`.
  |
| `scroll: {on | off | yes | no | 1 | 0 }` |
 If `on`, `yes`, or 1, the dialog window has scroll
 bars; otherwise its size is fixed. Default is `no`.
  |

**Note:** Firefox does not implement the `dialogHide`, `edge`, `status`, or `unadorned` arguments.

### Return value

Holds the `returnValue` property as set by the document specified by `uri`.

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

* MSDN page for `showModalDialog`
Browser compatibility
---------------------

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

See also
--------

* `<dialog>`, a replacement for `window.showModalDialog()`.
* showModalDialog Polyfill
 using a `<dialog>` and generators


Window: messageerror event - Web APIs

Window: messageerror event
==========================

The `messageerror` event is fired on a `Window` object when it receives a message that can't be deserialized.

This event is not cancellable and does not bubble.

Syntax
------

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

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

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

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

A `MessageEvent`. Inherits from `Event`.

Event

MessageEventEvent properties
----------------

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

`MessageEvent.data` Read only

The data sent by the message emitter.

`MessageEvent.origin` Read only

A string representing the origin of the message emitter.

`MessageEvent.lastEventId` Read only

A string representing a unique ID for the event.

`MessageEvent.source` Read only

A `MessageEventSource` (which can be a WindowProxy, `MessagePort`, or `ServiceWorker` object) representing the message emitter.

`MessageEvent.ports` Read only

An array of `MessagePort` objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker).

Examples
--------

Listen for `messageerror` using `addEventListener()`:

```js
window.addEventListener("messageerror", (event) => {
  console.error(event);
});
```

The same, but using the `onmessageerror` event handler property:

```js
window.onmessageerror = (event) => {
  console.error(event);
};
```

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

| Specification |
| --- |
| HTML Standard # event-messageerror |
| HTML Standard # handler-window-onmessageerror |

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

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

See also
--------

* `Window.postMessage()`
* Related events: `message`.


Window: toolbar property - Web APIs

Window: toolbar property
========================

Returns the `toolbar` 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-toolbar-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.scrollbars`
* `window.statusbar`


Window: resizeBy() method - Web APIs

Window: resizeBy() method
=========================

 The **`Window.resizeBy()`** method resizes the current window
 by a specified amount.

Syntax
------

```js
resizeBy(xDelta, yDelta)
```

### Parameters

* `xDelta` is the number of pixels to grow the window horizontally.
* `yDelta` is the number of pixels to grow the window vertically.
### Return value

None (`undefined`).

Examples
--------

```js
// Shrink the window
window.resizeBy(-200, -200);
```

Notes
-----

 This method resizes the window relative to its current size. To resize the window in
 absolute terms, use `window.resizeTo()`.

### Creating and resizing an external window

 For security reasons, it's no longer possible in Firefox for a website to change the
 default size of a window in a browser if the window wasn't created by
 `window.open()`, or contains more than one tab. See the compatibility table
 for details on the change.

 Even if you create window by `window.open()` **it is not resizable by
default.** To make the window resizable, you must open it with the
 `"resizable"` feature.

```js
// Create resizable window
myExternalWindow = window.open(
  "https://example.com",
  "myWindowName",
  "resizable",
);

// Resize window to 500x500
myExternalWindow.resizeTo(500, 500);

// Make window relatively smaller to 400x400
myExternalWindow.resizeBy(-100, -100);
```

 The window you create must respect the Same Origin Policy. If the window you open is
 not in the same origin as the current window, you will not be able to resize, or access
 any information on, that window/tab.

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

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

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

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


Window: prompt() method - Web APIs

Window: prompt() method
=======================

`window.prompt()` instructs the browser to display a dialog with an optional message prompting the user to input some text, and to wait until the user either submits the text or cancels the dialog.

Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to submit text or to cancel the dialog.

Syntax
------

```js
prompt()
prompt(message)
prompt(message, defaultValue)
```

### Parameters

`message` Optional

 A string of text to display to the user. Can be omitted if there is nothing to show
 in the prompt window.

`defaultValue` Optional

A string containing the default value displayed in the text input field.

### Return value

A string containing the text entered by the user, or `null`.

Examples
--------

```js
let sign = prompt("What's your sign?");

if (sign.toLowerCase() === "scorpio") {
  alert("Wow! I'm a Scorpio too!");
}

// there are many ways to use the prompt feature
sign = window.prompt(); // open the blank prompt window
sign = prompt(); // open the blank prompt window
sign = window.prompt("Are you feeling lucky"); // open the window with Text "Are you feeling lucky"
sign = window.prompt("Are you feeling lucky", "sure"); // open the window with Text "Are you feeling lucky" and default value "sure"
```

 When the user clicks the OK button, text entered in the input field is returned. If the
 user clicks OK without entering any text, an empty string is returned. If the user
 clicks the Cancel button, this function returns `null`.

The above prompt appears as follows (in Chrome on macOS):

![prompt() dialog in Chrome on macOS](/en-US/docs/Web/API/Window/prompt/prompt.png)

Notes
-----

 A prompt dialog contains a single-line textbox, a Cancel button, and an OK button, and
 returns the (possibly empty) text the user entered into that textbox.

 Please note that result is a string. That means you should sometimes cast the value
 given by the user. For example, if their answer should be a Number, you should cast the
 value to Number.

```js
const aNumber = Number(window.prompt("Type a number", ""));
```

 Dialog boxes are modal windows; they
 prevent the user from accessing the rest of the program's interface until the dialog box
 is closed. For this reason, you should not overuse any function that creates a dialog
 box (or modal window).

Alternatively `<dialog>` element can be used to take user inputs.

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

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

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

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

See also
--------

* `<dialog>` element
* `alert`
* `confirm`


Window: devicePixelRatio property - Web APIs

Window: devicePixelRatio property
=================================

 The **`devicePixelRatio`** of
 `Window` interface returns the ratio of the resolution in *physical
pixels* to the resolution in *CSS pixels* for the current display
 device.

 This value could also be interpreted as the ratio of pixel sizes: the
 size of one *CSS pixel* to the size of one *physical pixel*. In simpler
 terms, this tells the browser how many of the screen's actual pixels should be used to
 draw a single CSS pixel.

 This is useful when dealing with the difference between rendering on a standard display
 versus a HiDPI or Retina display, which use more screen pixels to draw the same objects,
 resulting in a sharper image.

 You can use `window.matchMedia()` to check if the
 value of `devicePixelRatio` changes (which can happen, for example, if the
 user drags the window to a display with a different pixel density). See
 the example below.

Value
-----

A double-precision floating-point value indicating the ratio of the display's resolution in physical pixels to the resolution in CSS pixels. A value of 1 indicates a classic 96 DPI display, while a value of 2 is expected for HiDPI/Retina displays.

Other values may be returned in the case of unusually low resolution displays or, more often, when a screen has a higher pixel density than double the standard resolution of 96 DPI. Modern mobile device screens - which offer high display resolutions at small physical sizes - often yield a `devicePixelRatio` value greater than 2.

Examples
--------

### Correcting resolution in a `<canvas>`

 A `<canvas>` can appear too blurry on retina screens.
 Use `window.devicePixelRatio` to determine how much extra pixel density
 should be added to allow for a sharper image.

#### HTML

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

#### JavaScript

```js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Set display size (css pixels).
const size = 200;
canvas.style.width = `${size}px`;
canvas.style.height = `${size}px`;

// Set actual size in memory (scaled to account for extra pixel density).
const scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas.
canvas.width = Math.floor(size \* scale);
canvas.height = Math.floor(size \* scale);

// Normalize coordinate system to use CSS pixels.
ctx.scale(scale, scale);

ctx.fillStyle = "#bada55";
ctx.fillRect(10, 10, 300, 300);
ctx.fillStyle = "#ffffff";
ctx.font = "18px Arial";
ctx.textAlign = "center";
ctx.textBaseline = "middle";

const x = size / 2;
const y = size / 2;

const textString = "I love MDN";
ctx.fillText(textString, x, y);
```

![Side-by-side comparison of the effect of different devicePixelRatio values on an image shown in a retina display.](/en-US/docs/Web/API/Window/devicePixelRatio/devicepixelratio_diff.png)

### Monitoring screen resolution or zoom level changes

In this example, we'll set up a media query and watch it to see when the device resolution changes, logging the new resolution.

#### HTML

```html
<div id="container">
  <p>
    This example demonstrates the effect of zooming the page in and out
    (or moving it to a screen with a different scaling factor) on the
    value of the <code>devicePixelRatio</code> property.</p>
    <p>Try it and watch what happens!</p>
  </p>
</div>
<div id="output"></div>
```

#### CSS

```css
body {
  font:
    22px arial,
    sans-serif;
}

#container {
  border: 2px solid #22d;
  margin: 1rem auto;
  padding: 1rem;
  background-color: #a9f;
}
```

#### JavaScript

The string `mqString` is set to a media query which checks to see if the current display resolution matches a specific number of device dots per `px`.

The `media` variable is a `MediaQueryList` object that's initialized with the media query string. When the result of running `mqString` against the document changes, the `media` object's `change` event fires, and the code logs the new resolution.

Note that every time the resolution changes, the example has to create a new media query, based on the new resolution, and a new `MediaQueryList` instance.

```js
let remove = null;
const output = document.querySelector("#output");

const updatePixelRatio = () => {
  if (remove != null) {
    remove();
  }
  const mqString = `(resolution: ${window.devicePixelRatio}dppx)`;
  const media = matchMedia(mqString);
  media.addEventListener("change", updatePixelRatio);
  remove = () => {
    media.removeEventListener("change", updatePixelRatio);
  };

  output.textContent = `devicePixelRatio: ${window.devicePixelRatio}`;
};

updatePixelRatio();
```

#### Result

To test the example, try zooming the page in and out, and note the difference in the logged value of `devicePixelRatio`.

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

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

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

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

See also
--------

* Media queries
* Using media queries
* CSS `resolution` media query
* The `image-resolution` property


Window: focus event - Web APIs

Window: focus event
===================

The **`focus`** event fires when an element has received focus.

The opposite of `focus` is `blur`.

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("focus", (event) => {});

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

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

A `FocusEvent`. Inherits from `UIEvent` and `Event`.

Event

UIEvent

FocusEventEvent properties
----------------

*This interface also inherits properties from its parent `UIEvent`, and indirectly from `Event`.*

`FocusEvent.relatedTarget`

An `EventTarget` representing a secondary target for this event. In some cases (such as when tabbing in or out a page), this property may be set to `null` for security reasons.

Examples
--------

### Live example

This example changes the appearance of a document when it loses focus. It uses `addEventListener()` to monitor `focus` and `blur` events.

#### HTML

```html
<p id="log">Click on this document to give it focus.</p>
```

#### CSS

```css
.paused {
  background: #ddd;
  color: #555;
}
```

#### JavaScript

```js
function pause() {
  document.body.classList.add("paused");
  log.textContent = "FOCUS LOST!";
}

function play() {
  document.body.classList.remove("paused");
  log.textContent =
    "This document has focus. Click outside the document to lose focus.";
}

const log = document.getElementById("log");

window.addEventListener("blur", pause);
window.addEventListener("focus", play);
```

#### Result

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

| Specification |
| --- |
| UI Events # event-type-focus |
| HTML Standard # handler-onfocus |

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

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

See also
--------

* Related event: `blur`
* This event on `Element` targets: `focus` event


Window: vrdisplayconnect event - Web APIs

Window: vrdisplayconnect 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.

**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 **`vrdisplayconnect`** event of the WebVR API is fired when a compatible VR display is connected to the computer.

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

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("vrdisplayconnect", (event) => {});

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

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

A `VRDisplayEvent`. Inherits from `Event`.

Event properties
----------------

*`VRDisplayEvent` also inherits properties from its parent object, `Event`.*

`VRDisplayEvent.display`
Deprecated
 Read only

The `VRDisplay` associated with this event.

`VRDisplayEvent.reason`
Deprecated
 Read only

A human-readable reason why the event was fired.

Examples
--------

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

```js
window.addEventListener("vrdisplayconnect", () => {
  info.textContent = "Display connected.";
  reportDisplays();
});
```

Or use the `onvrdisplayconnect` event handler property:

```js
window.onvrdisplayconnect = () => {
  info.textContent = "Display connected.";
  reportDisplays();
};
```

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

This event 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 Device API, 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


Window: moveTo() method - Web APIs

Window: moveTo() method
=======================

 The **`moveTo()`** method of the `Window`
 interface moves the current window to the specified coordinates.

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

Syntax
------

```js
moveTo(x, y)
```

### Parameters

* `x` is the horizontal coordinate to be moved to.
* `y` is the vertical coordinate to be moved to.
### Return value

None (`undefined`).

Examples
--------

This example moves the window to the top-left corner of the screen.

```js
function origin() {
  window.moveTo(0, 0);
}
```

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

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

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.moveBy()`


Window: beforeprint event - Web APIs

Window: beforeprint event
=========================

The **`beforeprint`** event is fired when the associated document is about to be printed or previewed for printing.

The `afterprint` and `beforeprint` events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed. In general, you should prefer the use of a `@media print` CSS at-rule, but it may be necessary to use these events in some cases.

Syntax
------

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

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

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

A generic `Event`.

Examples
--------

Using `addEventListener()`:

```js
window.addEventListener("beforeprint", (event) => {
  console.log("Before print");
});
```

Using the `onbeforeprint` event handler property:

```js
window.onbeforeprint = (event) => {
  console.log("Before print");
};
```

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

| Specification |
| --- |
| HTML Standard # event-beforeprint |
| HTML Standard # handler-window-onbeforeprint |

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

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

See also
--------

* Related events: `afterprint`


Window: pagehide event - Web APIs

Window: pagehide event
======================

The **`pagehide`** event is sent to a `Window` when the browser hides the current page in the process of presenting a different page from the session's history.

For example, when the user clicks the browser's Back button, the current page receives a `pagehide` event before the previous page is shown.

Syntax
------

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

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

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

A `PageTransitionEvent`. Inherits from `Event`.

Event

PageTransitionEventEvent properties
----------------

`PageTransitionEvent.persisted` Read only

Indicates if the document is loading from a cache.

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

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

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

 Like the `unload`
 and `beforeunload` events, this event is not reliably fired by browsers, especially on mobile. For example, the `pagehide` event is not fired at all in the following scenario:

1. A mobile user visits your page.
2. The user then switches to a different app.
3. Later, the user closes the browser from the app manager.

 However, unlike the `unload` and `beforeunload` events, this event is compatible with the back/forward cache (bfcache), so adding a listener to this event will not prevent the page
 from being included in the bfcache.

The best event to use to signal the end of a user's session is the `visibilitychange` event. In browsers that don't support `visibilitychange` the `pagehide` event is the next-best alternative.

If you're specifically trying to detect page unload events, the `pagehide` event is the best option.

See the Page Lifecycle API guide for more information about how this event relates to other events in the page lifecycle.

Examples
--------

In this example, an event handler is established to watch for `pagehide` events and to perform special handling if the page is being persisted for possible reuse.

```js
window.addEventListener(
  "pagehide",
  (event) => {
    if (event.persisted) {
      /\* the page isn't being discarded, so it can be reused later \*/
    }
  },
  false,
);
```

This can also be written using the `onpagehide` event handler property on the `Window`:

```js
window.onpagehide = (event) => {
  if (event.persisted) {
    /\* the page isn't being discarded, so it can be reused later \*/
  }
};
```

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

| Specification |
| --- |
| HTML Standard # event-pagehide |

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

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

See also
--------

* The `pageshow` event.
* Page Lifecycle API gives best-practices guidance on handling page lifecycle behavior in your web applications.
* PageLifecycle.js: a JavaScript library that deals with cross-browser inconsistencies in page lifecycle behavior.
* Back/forward cache explains what the back/forward cache is, and its implications for various page lifecycle events.


Window: sizeToContent() method - Web APIs

Window: sizeToContent() 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.sizeToContent()`** method sizes the window
 according to its content. In order for it to work, the DOM content should be loaded when
 this function is called—for example, once the `DOMContentLoaded` event has
 been thrown.

 Since Firefox 20, the minimal size of the window is clamped to prevent the window from
 being too small for the user to interact with.

Syntax
------

```js
sizeToContent()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
window.sizeToContent();
```

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

This feature is not part of any specification.

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

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

See also
--------

* `Window`


Window: localStorage property - Web APIs

Window: localStorage property
=============================

The **`localStorage`** read-only property of the `window` interface allows you to access a `Storage` object for the `Document`'s origin; the stored data is saved across browser sessions.

`localStorage` is similar to `sessionStorage`, except that while `localStorage` data has no expiration time, `sessionStorage` data gets cleared when the page session ends — that is, when the page is closed. (`localStorage` data for a document loaded in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.)

Value
-----

A `Storage` object which can be used to access the current origin's local storage space.

### Exceptions

`SecurityError`

Thrown in one of the following cases:

* The origin is not a valid scheme/host/port tuple. This can happen if the origin uses the `file:` or `data:` schemes, for example.
* The request violates a policy decision. For example, the user has configured the browsers to prevent the page from persisting data.

Note that if the user blocks cookies, browsers will probably interpret this as an instruction to prevent the page from persisting data.

Description
-----------

The keys and the values stored with `localStorage` are *always* in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.

`localStorage` data **is specific to the protocol of the document**. In particular, for a site loaded over HTTP (e.g., `http://example.com`), `localStorage` returns a different object than `localStorage` for the corresponding site loaded over HTTPS (e.g., `https://example.com`).

For documents loaded from `file:` URLs (that is, files opened in the browser directly from the user's local filesystem, rather than being served from a web server) the requirements for `localStorage` behavior are undefined and may vary among different browsers.

In all current browsers, `localStorage` seems to return a different object for each `file:` URL. In other words, each `file:` URL seems to have its own unique local-storage area. But there are no guarantees about that behavior, so you shouldn't rely on it because, as mentioned above, the requirements for `file:` URLs remain undefined. So it's possible that browsers may change their `file:` URL handling for `localStorage` at any time. In fact some browsers *have* changed their handling for it over time.

Examples
--------

The following snippet accesses the current domain's local `Storage` object and adds a data item to it using `Storage.setItem()`.

```js
localStorage.setItem("myCat", "Tom");
```

The syntax for reading the `localStorage` item is as follows:

```js
const cat = localStorage.getItem("myCat");
```

The syntax for removing the `localStorage` item is as follows:

```js
localStorage.removeItem("myCat");
```

The syntax for removing all the `localStorage` items is as follows:

```js
localStorage.clear();
```

**Note:** Please refer to the Using the Web Storage API article for a full example.

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

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

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

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

See also
--------

* Using the Web Storage API
* `Window.sessionStorage`


Window: stop() method - Web APIs

Window: stop() method
=====================

 The **`window.stop()`** stops further resource loading in the current
 browsing context, equivalent to the stop button in the browser.

 Because of how scripts are executed, this method cannot interrupt its parent
 document's loading, but it will stop its images, new windows, and other still-loading
 objects.

Syntax
------

```js
stop()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
window.stop();
```

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

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

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

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


Window: updateCommands() method - Web APIs

Window: updateCommands() 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.

Updates the state of commands of the current chrome window (UI).

Syntax
------

```js
updateCommands("sCommandName")
```

### Parameters

* `sCommandName` is a particular string which describes what kind of update event this is (e.g. whether we are in bold right now).
### Return value

None (`undefined`).

Notes
-----

This enables or disables items (setting or clearing the "disabled" attribute on the command node as appropriate), or ensures that the command state reflects the state of the selection by setting current state information in the "state" attribute of the XUL command nodes.

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.


Window: visualViewport property - Web APIs

Window: visualViewport property
===============================

The **`visualViewport`** read-only property of the `Window` interface returns a `VisualViewport` object representing the visual viewport for a given window, or `null` if current document is not fully active.

Value
-----

A `VisualViewport` object.

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

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

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

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


Window: navigator property - Web APIs

Window: navigator property
==========================

 The **`Window.navigator`** read-only property returns a
 reference to the `Navigator` object, which has methods and properties about
 the application running the script.

Value
-----

The `navigator` object.

Examples
--------

### Example 1: Browser detect and return a string

```js
function getBrowserName(userAgent) {
  // The order matters here, and this may report false positives for unlisted browsers.

  if (userAgent.includes("Firefox")) {
    // "Mozilla/5.0 (X11; Linux i686; rv:104.0) Gecko/20100101 Firefox/104.0"
    return "Mozilla Firefox";
  } else if (userAgent.includes("SamsungBrowser")) {
    // "Mozilla/5.0 (Linux; Android 9; SAMSUNG SM-G955F Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/9.4 Chrome/67.0.3396.87 Mobile Safari/537.36"
    return "Samsung Internet";
  } else if (userAgent.includes("Opera") || userAgent.includes("OPR")) {
    // "Mozilla/5.0 (Macintosh; Intel Mac OS X 12\_5\_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36 OPR/90.0.4480.54"
    return "Opera";
  } else if (userAgent.includes("Edge")) {
    // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299"
    return "Microsoft Edge (Legacy)";
  } else if (userAgent.includes("Edg")) {
    // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36 Edg/104.0.1293.70"
    return "Microsoft Edge (Chromium)";
  } else if (userAgent.includes("Chrome")) {
    // "Mozilla/5.0 (X11; Linux x86\_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
    return "Google Chrome or Chromium";
  } else if (userAgent.includes("Safari")) {
    // "Mozilla/5.0 (iPhone; CPU iPhone OS 15\_6\_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Mobile/15E148 Safari/604.1"
    return "Apple Safari";
  } else {
    return "unknown";
  }
}

const browserName = getBrowserName(navigator.userAgent);
console.log(`You are using: ${browserName}`);
```

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

| Specification |
| --- |
| HTML Standard # dom-navigator |

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

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


Window: storage event - Web APIs

Window: storage event
=====================

The **`storage`** event of the `Window` interface fires when a storage area (`localStorage` or `sessionStorage`) has been modified in the context of another document.

This event is not cancelable and does not bubble.

**Note:** This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.

Syntax
------

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

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

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

A `StorageEvent`. Inherits from `Event`.

Event

StorageEventEvent properties
----------------

`key` Read only

 Returns a string with the key for the storage item that was changed.
 The `key` attribute is `null` when the change is caused by the storage `clear()` method.

`newValue` Read only

 Returns a string with the new value of the storage item that was changed.
 This value is `null` when the change has been invoked by storage `clear()` method,
 or the storage item has been removed from the storage.

`oldValue` Read only

 Returns a string with the original value of the storage item that was changed.
 This value is `null` when the storage item has been newly added
 and therefore doesn't have any previous value.

`storageArea` Read only

Returns a `Storage` object that represents the storage object that was affected.

`url` Read only

Returns string with the URL of the document whose storage changed.

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

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

* `HTMLBodyElement`
* `HTMLFrameSetElement`
* `SVGSVGElement`
Examples
--------

Log the `sampleList` item to the console when the `storage` event fires:

```js
window.addEventListener("storage", () => {
  // When local storage changes, dump the list to
  // the console.
  console.log(JSON.parse(window.localStorage.getItem("sampleList")));
});
```

The same action can be achieved using the `onstorage` event handler property:

```js
window.onstorage = () => {
  // When local storage changes, dump the list to
  // the console.
  console.log(JSON.parse(window.localStorage.getItem("sampleList")));
};
```

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

| Specification |
| --- |
| HTML Standard # event-storage |
| HTML Standard # handler-window-onstorage |

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

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

See also
--------

* Web Storage API
* Using the Web Storage API
* Responding to storage changes with the StorageEvent


Window: sharedStorage property - Web APIs

Window: sharedStorage property
==============================

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

The global read-only **`sharedStorage`** property returns the `WindowSharedStorage` object for the current origin. This is the main entry point for writing data to shared storage using the Shared Storage API.

**Note:** `sharedStorage` is not available inside workers. It is implemented by `Window` and is also available in shared storage worklets (see `SharedStorageWorkletGlobalScope.sharedStorage`, which returns `WorkletSharedStorage`).

Value
-----

A `WindowSharedStorage` object instance.

Examples
--------

```js
window.sharedStorage
  .set("ab-testing-group", "0")
  .then(console.log("Value saved to shared storage"));
```

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

#### No specification found

No specification data found for `api.Window.sharedStorage`.
Check for problems with this page or contribute a missing `spec_url` to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

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

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

See also
--------

* `WindowSharedStorage`
* Shared Storage API


Window: appinstalled event - Web APIs

Window: appinstalled event
==========================

The **`appinstalled`** event of the Web Manifest API is fired when the browser has successfully installed a page as an application.

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("appinstalled", (event) => {});

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

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

A generic `Event`.

Examples
--------

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

```js
window.addEventListener("appinstalled", () => {
  console.log("Thank you for installing our app!");
});
```

Or use the `onappinstalled` event handler property:

```js
window.onappinstalled = () => {
  console.log("Thank you for installing our app!");
};
```

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

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


Window: outerWidth property - Web APIs

Window: outerWidth property
===========================

**`Window.outerWidth`** read-only property returns the width of the outside of the browser window. It represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles.

Notes
-----

To change the size of a window, see `window.resizeBy()` and `window.resizeTo()`.

To get the inner width of a window, i.e. the width of the page being displayed, see `window.innerWidth`.

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

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

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

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

See also
--------

* `window.outerHeight`, `window.innerHeight`, `window.innerWidth`
* `window.resizeBy()`, `window.resizeTo()`


Window: devicemotion event - Web APIs

Window: devicemotion event
==========================

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

The **`devicemotion`** event is fired at a regular interval and indicates the amount of physical force of acceleration the device is receiving at that time. It also provides information about the rate of rotation, if available.

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("devicemotion", (event) => {});

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

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

A `DeviceMotionEvent`. Inherits from `Event`.

Event

DeviceMotionEventEvent properties
----------------

`DeviceMotionEvent.acceleration` Read only

An object giving the acceleration of the device on the three axis: x, y, and z. Acceleration is expressed in m/s².

`DeviceMotionEvent.accelerationIncludingGravity` Read only

An object giving the acceleration of the device on the three axis: x, y, and z with the effect of gravity. Acceleration is expressed in m/s².

`DeviceMotionEvent.rotationRate` Read only

An object giving the rate of change of the device's orientation on the three orientation axis: alpha, beta and gamma. Rotation rate is expressed in degrees per seconds.

`DeviceMotionEvent.interval` Read only

A number representing the interval of time, in milliseconds, at which data is obtained from the device.

Examples
--------

```js
function handleMotionEvent(event) {
  const x = event.accelerationIncludingGravity.x;
  const y = event.accelerationIncludingGravity.y;
  const z = event.accelerationIncludingGravity.z;

  // Do something awesome.
}

window.addEventListener("devicemotion", handleMotionEvent, true);
```

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

| Specification |
| --- |
| DeviceOrientation Event Specification # devicemotion |
| DeviceOrientation Event Specification # ref-for-dom-window-ondevicemotion |

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

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

See also
--------

* `deviceorientation`
* DeviceOrientation Event


Window: forward() method - Web APIs

Window: forward() 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.

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

Moves the window one document forward in history. This was a Firefox-specific method and was removed in Firefox 31.

**Note:** Use the standard `history.forward()` method instead.

Syntax
------

```js
forward()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
function goForward() {
  if (canGoForward) {
    window.forward();
  }
}
```

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

This is not part of any specification.

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

This non-standard method was only implemented in Firefox, and was removed in Firefox 31.

See also
--------

* `History.back()`
* `History.forward()`


Window: getComputedStyle() method - Web APIs

Window: getComputedStyle() method
=================================

 The
 **`Window.getComputedStyle()`** method returns an object
 containing the values of all CSS properties of an element, after applying active
 stylesheets and resolving any basic computation those values may contain.

 Individual CSS property values are accessed through APIs provided by the object, or by
 indexing with CSS property names.

Syntax
------

```js
getComputedStyle(element)
getComputedStyle(element, pseudoElt)
```

### Parameters

`element`

The `Element` for which to get the computed style.

`pseudoElt` Optional

 A string specifying the pseudo-element to match. Omitted (or `null`) for
 real elements.

### Return value

 A *live* `CSSStyleDeclaration`
 object, which updates automatically when the element's styles are changed.

### Exceptions

`TypeError`

 If the passed object is not an `Element` or the
 `pseudoElt` is not a valid pseudo-element selector or is
 `::part()` or `::slotted()`.

**Note:** Valid pseudo-element selector refers to syntactic
 validity, e.g. `::unsupported` is considered valid, even though the
 pseudo-element itself is not supported. Additionally, the latest W3 standard explicitly supports only `::before` and `::after`, while the CSS
 WG draft does not restrict this value. Browser compatibility may vary.

Examples
--------

 In this example we style a `<p>` element, then retrieve those styles
 using `getComputedStyle()`, and print them into the text content of the
 `<p>`.

### HTML

```html
<p>Hello</p>
```

### CSS

```css
p {
  width: 400px;
  margin: 0 auto;
  padding: 20px;
  font: 2rem/2 sans-serif;
  text-align: center;
  background: purple;
  color: white;
}
```

### JavaScript

```js
const para = document.querySelector("p");
const compStyles = window.getComputedStyle(para);
para.textContent =
  `My computed font-size is ${compStyles.getPropertyValue("font-size")},\n` +
  `and my computed line-height is ${compStyles.getPropertyValue(
 "line-height",
 )}.`;
```

### Result

Description
-----------

 The returned object is the same `CSSStyleDeclaration` type as the object
 returned from the element's `style` property. However,
 the two objects have different purposes:

* The object from `getComputedStyle` is read-only, and should be used to
 inspect the element's style — including those set by a `<style>`
 element or an external stylesheet.
* The `element.style` object should be used to
 **set** styles on that element, or inspect styles directly added to it
 from JavaScript manipulation or the global `style` attribute.

 The first argument must be an `Element`. Non-elements, like a
 `Text` node, will throw an error.

defaultView
-----------

 In many code samples, `getComputedStyle` is used from the
 `document.defaultView` object. In nearly all cases, this is needless, as
 `getComputedStyle` exists on the `window` object as well. It's
 likely the `defaultView` pattern was a combination of folks not wanting to
 write a testing spec for `window` and making an API that was also usable in
 Java.

Use with pseudo-elements
------------------------

`getComputedStyle` can pull style info from pseudo-elements (such as
 `::after`, `::before`, `::marker`,
 `::line-marker` — see the pseudo-element spec).

```html
<style>
 h3::after {
 content: " rocks!";
 }
</style>

<h3>Generated content</h3>

<script>
 const h3 = document.querySelector("h3");
 const result = getComputedStyle(h3, ":after").content;

 console.log("the generated content is: ", result); // returns ' rocks!'
</script>
```

Notes
-----

* The returned `CSSStyleDeclaration` object contains active values for
 CSS property ***longhand*** names. For example,
 `border-bottom-width` instead of the `border-width` and
 `border` shorthand property names. It is safest to query values with only longhand names like
 `font-size`. Shorthand names like `font` will not work with most
 browsers.
* CSS property values may be accessed using the
 `getPropertyValue(propName)` API or by indexing directly into the object
 such as `obj['z-index']` or `obj.zIndex`.
* The values returned by `getComputedStyle` are `resolved values`. These are usually the same as CSS 2.1's
 `computed values`, but for some older properties
 like `width`, `height`, or `padding`, they are
 instead the same as `used values`. Originally, CSS
 2.0 defined the *computed values* as the "ready to be used" final values of
 properties after cascading and inheritance, but CSS 2.1 redefined them as pre-layout,
 and *used values* as post-layout. For CSS 2.0 properties,
 `getComputedStyle` returns the old meaning of computed values, now called
 **used values**. An example difference between pre- and post-layout
 values includes the resolution of percentages for `width` or
 `height`, as those will be replaced by their pixel equivalent only for
 *used values*.
* Returned values are sometimes deliberately inaccurate. To avoid the "CSS History
 Leak" security issue, browsers may lie about the computed styles for a visited link,
 returning values as if the user never visited the linked URL. See Plugging the CSS History Leak and Privacy-related changes coming to CSS :visited for examples of how this is implemented.
* During CSS transitions,
 `getComputedStyle` returns the original property value in Firefox, but the
 final property value in WebKit.
* In Firefox, properties with the value `auto` return the used value, not
 the value `auto`. So if you apply `top:auto` and
 `bottom:0` on an element with `height:30px` and a containing
 block of `height:100px`, Firefox's computed style for `top`
 returns `70px`, as 100 − 30 = 70.
Specifications
--------------

| Specification |
| --- |
| CSS Object Model (CSSOM) # dom-window-getcomputedstyle |

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

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

See also
--------

* `window.getDefaultComputedStyle`
* `Resolved Value`


Window: vrdisplayactivate event - Web APIs

Window: vrdisplayactivate 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.

**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 **`vrdisplayactivate`** event of the WebVR API is fired when a VR display is able to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on.

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

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("vrdisplayactivate", (event) => {});

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

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

A `VRDisplayEvent`. Inherits from `Event`.

Event properties
----------------

*`VRDisplayEvent` also inherits properties from its parent object, `Event`.*

`VRDisplayEvent.display`
Deprecated
 Read only

The `VRDisplay` associated with this event.

`VRDisplayEvent.reason`
Deprecated
 Read only

A human-readable reason why the event was fired.

Examples
--------

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

```js
window.addEventListener("vrdisplayactivate", () => {
  info.textContent = "Display activated.";
  reportDisplays();
});
```

Or use the `onvrdisplayactivate` event handler property:

```js
window.onvrdisplayactivate = () => {
  info.textContent = "Display activated.";
  reportDisplays();
};
```

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

This event 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 Device API, 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


Window: screen property - Web APIs

Window: screen property
=======================

 The `Window` property **`screen`** returns a
 reference to the screen object associated with the window. The `screen`
 object, implementing the `Screen` interface, is a special object for
 inspecting properties of the screen on which the current window is being rendered.

Value
-----

A `Screen` object.

Examples
--------

```js
if (screen.pixelDepth < 8) {
  // use low-color version of page
} else {
  // use regular, colorful page
}
```

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

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

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

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


Window: cut event - Web APIs

Window: cut event
=================

The **`cut`** event is fired when the user has initiated a "cut" action through the browser's user interface.

The original target for this event is the `Element` that was the intended target of the cut action. You can listen for this event on the `Window` interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the Element: cut event.

Syntax
------

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

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

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

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

A `ClipboardEvent`. Inherits from `Event`.

Event

ClipboardEventExamples
--------

```js
window.addEventListener("cut", (event) => {
  console.log("cut action initiated");
});
```

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

| Specification |
| --- |
| Clipboard API and events # clipboard-event-cut |
| HTML Standard # handler-oncut |

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

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

See also
--------

* Related events: `copy`, `paste`
* This event on `Element` targets: `cut`
* This event on `Document` targets: `cut`


Window: fullScreen property - Web APIs

Window: fullScreen 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 **`fullScreen`** property of the `Window`
 interface indicates whether the window is displayed in full screen mode or not.

Value
-----

A boolean value with `true` meaning that the window is in full-screen mode and `false` meaning it isn't.

Notes
-----

* Switching between regular window and full screen will fire the "resize" event on the
 corresponding window.
Examples
--------

```js
if (window.fullScreen) {
  // it's fullscreen!
} else {
  // not fullscreen!
}
```

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

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


Window: cancelAnimationFrame() method - Web APIs

Window: cancelAnimationFrame() method
=====================================

 The **`window.cancelAnimationFrame()`** method cancels an
 animation frame request previously scheduled through a call to
 `window.requestAnimationFrame()`.

Syntax
------

```js
cancelAnimationFrame(requestID)
```

### Parameters

`requestID`

 The ID value returned by the call to `window.requestAnimationFrame()`
 that requested the callback.

### Return value

None (`undefined`).

Examples
--------

```js
const requestAnimationFrame =
  window.requestAnimationFrame ||
  window.mozRequestAnimationFrame ||
  window.webkitRequestAnimationFrame ||
  window.msRequestAnimationFrame;

const cancelAnimationFrame =
  window.cancelAnimationFrame || window.mozCancelAnimationFrame;

const start = Date.now();

let myReq;

function step(timestamp) {
  const progress = timestamp - start;
  d.style.left = `${Math.min(progress / 10, 200)}px`;
  if (progress < 2000) {
    // it's important to update the requestId each time you're calling requestAnimationFrame
    myReq = requestAnimationFrame(step);
  }
}
myReq = requestAnimationFrame(step);
// the cancellation uses the last requestId
cancelAnimationFrame(myReq);
```

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

| Specification |
| --- |
| HTML Standard # animationframeprovider-cancelanimationframe |

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

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

See also
--------

* `Window.requestAnimationFrame()`
* `DedicatedWorkerGlobalScope.cancelAnimationFrame()`