Window: vrdisplaydisconnect event - Web APIs

Window: vrdisplaydisconnect 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 **`vrdisplaydisconnect`** event of the WebVR API is fired when a compatible VR display is disconnected from the computer.

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

onvrdisplaydisconnect = (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 `vrdisplaydisconnect` event in an `addEventListener` method:

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

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

Or use the `onvrdisplaydisconnect` event handler property:

```js
window.onvrdisplaydisconnect = () => {
  info.textContent = "Display disconnected.";
  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: online event - Web APIs

Window: online event
====================

The **`online`** event of the `Window` interface is fired when the browser has gained access to the network and the value of `Navigator.onLine` switches to `true`.

**Note:** This event shouldn't be used to determine the availability of a particular website. Network problems or firewalls might still prevent the website from being reached.

Syntax
------

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

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

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

A generic `Event`.

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

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

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

```js
// addEventListener version
window.addEventListener("online", (event) => {
  console.log("You are now connected to the network.");
});

// ononline version
window.ononline = (event) => {
  console.log("You are now connected to the network.");
};
```

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

| Specification |
| --- |
| HTML Standard # event-online |
| HTML Standard # handler-window-ononline |

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

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

See also
--------

* `offline`


Window: screenX property - Web APIs

Window: screenX property
========================

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

**Note:** An alias of `screenX` was implemented across modern
 browsers in more recent times — `Window.screenLeft`. This was originally
 supported only in IE but was introduced everywhere due to popularity.

Value
-----

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

Examples
--------

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

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

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

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

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

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

  window.requestAnimationFrame(positionElem);
}

window.requestAnimationFrame(positionElem);
```

These work in exactly the same way as `screenX`/`screenY`.

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

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

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

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

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

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

See also
--------

* `window.screenLeft`
* `Window.screenY`


Window: open() method - Web APIs

Window: open() method
=====================

The **`open()`** method of the `Window` interface loads a specified resource into a new or existing browsing context (that is, a tab, a window, or an iframe) under a specified name.

Syntax
------

```js
open()
open(url)
open(url, target)
open(url, target, windowFeatures)
```

### Parameters

`url` Optional

A string indicating the URL or path of the resource to be loaded. If an empty string (`""`) is specified or this parameter is omitted, a blank page is opened into the targeted browsing context.

`target` Optional

A string, without whitespace, specifying the name of the browsing context the resource is being loaded into. If the name doesn't identify an existing context, a new context is created and given the specified name. The special `target` keywords, `_self`, `_blank`, `_parent`, and `_top`, can also be used.

This name can be used as the `target` attribute of `<a>` or `<form>` elements.

`windowFeatures` Optional

A string containing a comma-separated list of window features in the form `name=value` — or for boolean features, just `name`. These features include options such as the window's default size and position, whether or not to open a minimal popup window, and so forth. The following options are supported:

`popup`

If this feature is enabled, it requests that a minimal popup window be used. The UI features included in the popup window will be automatically decided by the browser, generally including an address bar only.

If `popup` is not enabled, and there are no window features declared, the new browsing context will be a tab.

**Note:** Specifying any features in the `windowFeatures` parameter, other than `noopener` or `noreferrer`, also has the effect of requesting a popup.

To enable the feature, specify `popup` either with no value at all, or else set it to `yes`, `1`, or `true`.

Example: `popup=yes`, `popup=1`, `popup=true`, and `popup` all have identical results.

`width` or `innerWidth`

Specifies the width of the content area, including scrollbars. The minimum required value is 100.

`height` or `innerHeight`

Specifies the height of the content area, including scrollbars. The minimum required value is 100.

`left` or `screenX`

Specifies the distance in pixels from the left side of the work area as defined by the user's operating system where the new window will be generated.

`top` or `screenY`

Specifies the distance in pixels from the top side of the work area as defined by the user's operating system where the new window will be generated.

`noopener`

If this feature is set, the new window will not have access to the originating window via `Window.opener` and returns `null`.

When `noopener` is used, non-empty target names, other than `_top`, `_self`, and `_parent`, are treated like `_blank` in terms of deciding whether to open a new browsing context.

`noreferrer`

If this feature is set, the browser will omit the `Referer` header, as well as set `noopener` to true. See `rel="noreferrer"` for more information.

**Note:** Requested position (`top`, `left`), and requested dimension (`width`, `height`) values in `windowFeatures` **will be corrected** if any of such requested value does not allow the entire browser popup to be rendered within the work area for applications of the user's operating system. In other words, no part of the new popup can be initially positioned offscreen.

### Return value

If the browser successfully opens the new browsing context, a `WindowProxy` object is returned. The returned reference can be used to access properties and methods of the new context as long as it complies with the same-origin policy security requirements.

`null` is returned if the browser fails to open the new browsing context, for example because it was blocked by a browser popup blocker.

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

The `Window` interface's `open()` method takes a URL as a parameter, and loads the resource it identifies into a new or existing tab or window. The `target` parameter determines which window or tab to load the resource into, and the `windowFeatures` parameter can be used to control to open a new popup with minimal UI features and control its size and position.

Remote URLs won't load immediately. When `window.open()` returns, the window always contains `about:blank`. The actual fetching of the URL is deferred and starts after the current script block finishes executing. The window creation and the loading of the referenced resource are done asynchronously.

Modern browsers have strict popup blocker policies. Popup windows must be opened in direct response to user input, and a separate user gesture event is required for each `Window.open()` call. This prevents sites from spamming users with lots of windows. However, this poses an issue for multi-window applications. To work around this limitation, you can design your applications to:

* Open no more than one new window at once.
* Reuse existing windows to display different pages.
* Advise users on how to update their browser settings to allow multiple windows.
Examples
--------

### Opening a new tab

```js
window.open("https://www.mozilla.org/", "mozillaTab");
```

### Opening a popup

Alternatively, the following example demonstrates how to open a popup, using the `popup` feature.

```js
window.open("https://www.mozilla.org/", "mozillaWindow", "popup");
```

It is possible to control the size and position of the new popup:

```js
const windowFeatures = "left=100,top=100,width=320,height=320";
const handle = window.open(
  "https://www.mozilla.org/",
  "mozillaWindow",
  windowFeatures,
);
if (!handle) {
  // The window wasn't allowed to open
  // This is likely caused by built-in popup blockers.
  // …
}
```

Progressive enhancement
-----------------------

In some cases, JavaScript is disabled or unavailable and `window.open()` will not work. Instead of solely relying on the presence of this feature, we can provide an alternative solution so that the site or application still functions.

### Provide alternative ways when JavaScript is disabled

If JavaScript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to its handling of the `target` attribute. The goal and the idea are to provide (and *not impose*) to the user a way to open the referenced resource.

#### HTML

```html
<a href="https://www.wikipedia.org/" target="OpenWikipediaWindow">
  Wikipedia, a free encyclopedia (opens in another, possibly already existing,
  tab)
</a>
```

#### JavaScript

```js
let windowObjectReference = null; // global variable
function openRequestedTab(url, windowName) {
  if (windowObjectReference === null || windowObjectReference.closed) {
    windowObjectReference = window.open(url, windowName);
  } else {
    windowObjectReference.focus();
  }
}

const link = document.querySelector("a[target='OpenWikipediaWindow']");
link.addEventListener(
  "click",
  (event) => {
    openRequestedTab(link.href);
    event.preventDefault();
  },
  false,
);
```

The above code solves a few usability problems related to links opening popups. The purpose of the `event.preventDefault()` in the code is to cancel the default action of the link: if the event listener for `click` is executed, then there is no need to execute the default action of the link. But if JavaScript support is disabled or non-existent on the user's browser, then the event listener for `click` is ignored, and the browser loads the referenced resource in the target frame or window that has the name `"WikipediaWindowName"`. If no frame nor window has the name `"WikipediaWindowName"`, then the browser will create a new window and name it `"WikipediaWindowName"`.

**Note:** For more details about the `target` attribute, see `<a>` or `<form>`.

### Reuse existing windows and avoid `target="_blank"`

Using `"_blank"` as the target attribute value will create several new and unnamed windows on the user's desktop that cannot be recycled or reused. Try to provide a meaningful name to your `target` attribute and reuse such `target` attribute on your page so that a click on another link may load the referenced resource in an already created and rendered window (therefore speeding up the process for the user) and therefore justifying the reason (and user system resources, time spent) for creating a secondary window in the first place. Using a single `target` attribute value and reusing it in links is much more user resources friendly as it only creates one single secondary window, which is recycled.

Here is an example where a secondary window can be opened and reused for other links:

#### HTML

```html
<p>
  <a href="https://www.wikipedia.org/" target="SingleSecondaryWindowName">
    Wikipedia, a free encyclopedia (opens in another, possibly already existing,
    tab)
  </a>
</p>
<p>
  <a
 href="https://support.mozilla.org/products/firefox"
 target="SingleSecondaryWindowName">
    Firefox FAQ (opens in another, possibly already existing, tab)
  </a>
</p>
```

#### JavaScript

```js
let windowObjectReference = null; // global variable
let previousURL; /\* global variable that will store the
 url currently in the secondary window \*/
function openRequestedSingleTab(url) {
  if (windowObjectReference === null || windowObjectReference.closed) {
    windowObjectReference = window.open(url, "SingleSecondaryWindowName");
  } else if (previousURL !== url) {
    windowObjectReference = window.open(url, "SingleSecondaryWindowName");
    /\* if the resource to load is different,
 then we load it in the already opened secondary window and then
 we bring such window back on top/in front of its parent window. \*/
    windowObjectReference.focus();
  } else {
    windowObjectReference.focus();
  }
  previousURL = url;
  /\* explanation: we store the current url in order to compare url
 in the event of another call of this function. \*/
}

const links = document.querySelectorAll(
  "a[target='SingleSecondaryWindowName']",
);
for (const link of links) {
  link.addEventListener(
    "click",
    (event) => {
      openRequestedSingleTab(link.href);
      event.preventDefault();
    },
    false,
  );
}
```

Same-origin policy
------------------

If the newly opened browsing context does not share the same origin, the opening script will not be able to interact (reading or writing) with the browsing context's content.

```js
// Script from example.com
const otherOriginContext = window.open("https://example.org");
// example.com and example.org are not the same origin

console.log(otherOriginContext.origin);
// DOMException: Permission denied to access property "origin" on cross-origin object
```

```js
// Script from example.com
const sameOriginContext = window.open("https://example.com");
// This time, the new browsing context has the same origin

console.log(sameOriginContext.origin);
// https://example.com
```

For more information, refer to the Same-origin policy article.

Accessibility concerns
----------------------

### Avoid resorting to window.open()

It is preferable to avoid resorting to `window.open()`, for several reasons:

* Modern browsers offer a popup-blocking feature.
* Modern browsers offer tab-browsing, and tab-capable browser users prefer opening new tabs to opening new windows in most situations.
* Users may use browser built-in features or extensions to choose whether to open a link in a new window, in the same window, in a new tab, the same tab, or in the background. Forcing the opening to happen in a specific way, using `window.open()`, will confuse them and disregard their habits.
* Popups don't have a menu toolbar, whereas new tabs use the user interface of the browser window; therefore, many users prefer tab-browsing because the interface remains stable.
### Never use window.open() inline in HTML

Avoid `<a href="#" onclick="window.open(…);">` or `<a href="javascript:window\.open(…)" …>`.

These bogus `href` values cause unexpected behavior when copying/dragging links, opening links in a new tab/window, bookmarking, or when JavaScript is loading, errors, or is disabled. They also convey incorrect semantics to assistive technologies, like screen readers.

If necessary, use a `<button>` element instead. In general, *you should only use a link for navigation to a real URL*.

### Always identify links leading to a secondary window

Identify links that will open new windows in a way that helps navigation for users.

```html
<a target="WikipediaWindow" href="https://www.wikipedia.org">
  Wikipedia (opens in new tab)
</a>
```

The purpose is to warn users of context changes to minimize confusion on the user's part: changing the current window or popping up new windows can be very disorienting to users (in the case of a popup, no toolbar provides a "Previous" button to get back to the previous window).

When extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in "background" or not).

* WebAIM: Links and Hypertext - Hypertext Links
* MDN / Understanding WCAG, Guideline 3.2
* G200: Opening new windows and tabs from a link only when necessary
* G201: Giving users advanced warning when opening a new window
Specifications
--------------

| Specification |
| --- |
| HTML Standard # dom-open-dev |
| CSSOM View Module # the-features-argument-to-the-open()-method |

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

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

See also
--------

* `target` attribute documentation:
    + `<a>`
    + `<form>`
* `window.close()`
* `window.closed`
* `window.focus()`
* `window.opener`
* `rel="opener"` and `rel="noopener"`
* Same-origin policy


Window: blur event - Web APIs

Window: blur event
==================

The **`blur`** event fires when an element has lost focus.

The opposite of `blur` is `focus`.

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

onblur = (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-blur |
| HTML Standard # handler-onblur |

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

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

The value of `Document.activeElement` varies across browsers while this event is being handled (Firefox bug 452307): IE10 sets it to the element that the focus will move to, while Firefox and Chrome often set it to the `body` of the document.

See also
--------

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


Window: webkitConvertPointFromNodeToPage() method - Web APIs

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

Given a `WebKitPoint` specified in a particular DOM `Node`'s coordinate system, the `Window` method **`webkitConvertPointFromNodeToPage()`** returns a `Point` which specifies the same position in the page's coordinate system. This method is non-standard and *should not be used*.

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

Syntax
------

```js
webkitConvertPointFromNodeToPage(node, nodePoint)
```

### Parameters

`node`

The `Node` in whose coordinate system the `Point` specified by `nodePoint` is described.

`nodePoint`

A `WebKitPoint` object describing a point in `node`'s coordinate system; this point will be converted to the page's coordinate system.

### Return value

A `WebKitPoint` object specifying a point in the page's coordinate system.

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

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

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

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

See also
--------

* `Window.webkitConvertPointFromPageToNode`
* Mozilla implementation bug: Firefox bug 850806


Window: status property - Web APIs

Window: status 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 **`status`** property of the
 `Window` interface was originally intended to set the text in the status
 bar at the bottom of the browser window. However, the HTML standard now requires
 setting `window.status` to have no effect on the text displayed in the
 status bar.

Value
-----

A string.

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

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

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

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


Window: getScreenDetails() method - Web APIs

Window: getScreenDetails() method
=================================

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

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

 The **`getScreenDetails()`** method of the
 `Window` interface returns a `Promise` that fulfills with a `ScreenDetails` object instance representing the details of all the screens available to the user's device.

Syntax
------

```js
getScreenDetails()
```

### Parameters

None.

### Return value

A `Promise` that fulfills with a `ScreenDetails` object instance.

### Exceptions

`NotAllowedError` `DOMException`

Thrown if a `window-management` Permissions-Policy is set that blocks use of the Window Management API, or if the user has explicitly denied the browser's permission request to use the API.

Examples
--------

When `getScreenDetails()` is invoked, the user will be asked for permission to manage windows on all their displays (the status of this permission can be checked using `Permissions.query()` to query `window-management`). Provided they grant permission, the resulting `ScreenDetails` object contains details of all the screens available to the user's system.

The below example opens a full-size window on each available display.

```js
const screenDetails = await window.getScreenDetails();

// Open a full-size window on each screen available to the device
for (const screen of screenDetails.screens) {
  window.open(
    "https://example.com",
    "\_blank",
    `left=${screen.availLeft},
 top=${screen.availTop},
 width=${screen.availWidth},
 height=${screen.availHeight}`,
  );
}
```

**Note:** See Multi-window learning environment for a full example (see the source code also).

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

| Specification |
| --- |
| Window Management # api-window-getScreenDetails-method |

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

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

See also
--------

* Window Management API


Window: unload event - Web APIs

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

**Warning:** Developers should avoid using this event. See "Usage notes" below.

The **`unload`** event is fired when the document or a child resource is being unloaded.

It is fired after:

* `beforeunload` (cancelable event)
* `pagehide`

The document is in the following state:

* All the resources still exist (img, iframe etc.)
* Nothing is visible anymore to the end user
* UI interactions are ineffective (`window.open`, `alert`, `confirm`, etc.)
* An error won't stop the unloading workflow

Please note that the unload event also follows the document tree: parent frame unload will happen **before** child frame `unload` (see example below).

Syntax
------

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

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

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

A generic `Event`.

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

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

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

Developers should avoid using this event.

Especially on mobile, the `unload` event is not reliably fired. For example, the `unload` 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.

Also, the `unload` event is not compatible with the back/forward cache (bfcache), because many pages using this event assume that the page will not continue to exist after the event is fired. To combat this, some browsers (such as Firefox) will not place pages in the bfcache if they have unload listeners, and this is bad for performance. Others, such as Chrome, will not fire the `unload` when a user navigates away.

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 next-best alternative is the `pagehide` event, which is also not fired reliably, but which is bfcache-compatible.

If you're specifically trying to detect page unload events, it's best to listen for the `pagehide` event.

See the Page Lifecycle API guide for more information about the problems associated with the `unload` event.

Examples
--------

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>Parent Frame</title>
    <script>
 window.addEventListener("beforeunload", (event) => {
 console.log("I am the 1st one.");
 });
 window.addEventListener("unload", (event) => {
 console.log("I am the 3rd one.");
 });
 </script>
  </head>
  <body>
    <iframe src="child-frame.html"></iframe>
  </body>
</html>
```

Below, the content of `child-frame.html`:

```html
<!doctype html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>Child Frame</title>
    <script>
 window.addEventListener("beforeunload", (event) => {
 console.log("I am the 2nd one.");
 });
 window.addEventListener("unload", (event) => {
 console.log("I am the 4th and last one…");
 });
 </script>
  </head>
  <body>
    ☻
  </body>
</html>
```

When the parent frame is unloaded, events will be fired in the order described by the `console.log()` messages.

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

| Specification |
| --- |
| HTML Standard # event-unload |
| HTML Standard # handler-window-onunload |

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

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

See also
--------

* Related events: `DOMContentLoaded`, `readystatechange`, `load`
* Unloading Documents — unload a document
* The `visibilitychange` event.
* Don't lose user and app state, use Page Visibility explains in
 detail why you should use `visibilitychange`, not
 `beforeunload`/`unload`.
* 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: name property - Web APIs

Window: name property
=====================

 The `Window.name` property
 gets/sets the name of the window's browsing context.

Value
-----

A string.

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

 The name of the window is used primarily for setting targets for hyperlinks and forms.
 Browsing contexts do not need to have names.

 Modern browsers will reset `Window.name` to an empty string if a tab loads a
 page from a different domain, and restore the name if the original page is reloaded
 (e.g. by selecting the "back" button). This prevents an untrusted page from accessing
 any information that the previous page might have stored in the property (potentially
 the new page might also modify such data, which might then be read by the original page
 if it was reloaded).

`Window.name` has also been used in some frameworks for providing
 cross-domain messaging
 as a more secure alternative to JSONP. Modern web applications hosting sensitive data
 should, however, not rely on `window.name` for cross-domain messaging — that
 is not its intended purpose and there are safer/better ways of sharing information
 between windows.
 `Window.postMessage()`
 is the recommended mechanism.

**Note:** `window.name` converts all stored values to their
 string representations using the `toString` method.

Examples
--------

```html
<script>
 // Open a tab with a specific browsing context name
 const otherTab = window.open("url1", "\_blank");
 if (otherTab) otherTab.name = "other-tab";
</script>
<a href="url2" target="other-tab">This link will be opened in the other tab.</a>
```

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

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

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

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


Window: showDirectoryPicker() method - Web APIs

Window: showDirectoryPicker() 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 **`showDirectoryPicker()`** method of the
 `Window` interface displays a directory picker which allows the user to
 select a directory.

Syntax
------

```js
showDirectoryPicker()
```

### Parameters

`options` Optional

An object containing options, which are as follows:

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

`mode` Optional

 A string that defaults to `"read"` for read-only access or `"readwrite"` for read
 and write access to the directory.

`startIn` Optional

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

### Return value

A `Promise` whose fulfillment handler receives a `FileSystemDirectoryHandle` object.

### Exceptions

`AbortError` `DOMException`

 Thrown if the user dismisses the prompt without making a selection,
 or if the user agent deems the selected directory to be too sensitive or dangerous,
 or if the `PermissionStatus.state` for the selected directory is not `"granted"` in the specified `mode`.

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

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

 This asynchronous function shows a directory picker and returns a
 `FileSystemDirectoryHandle` once selected.

```js
async function getDir() {
  const dirHandle = await window.showDirectoryPicker();

  // run code for dirHandle
}
```

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

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

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: top property - Web APIs

Window: top property
====================

Returns a reference to the topmost window in the window hierarchy.

Value
-----

The reference to the topmost window.

Notes
-----

 Where the `window.parent` property returns the immediate parent of the
 current window, `window.top` returns the topmost window in the hierarchy of
 window objects.

 This property is especially useful when you are dealing with a window that is in a
 subframe of a parent or parents, and you want to get to the top-level frameset.

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

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

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

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


Window: hashchange event - Web APIs

Window: hashchange event
========================

The **`hashchange`** event is fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the `#` symbol).

Syntax
------

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

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

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

A `HashChangeEvent`. Inherits from `Event`.

Event

HashChangeEventEvent properties
----------------

`HashChangeEvent.newURL` Read only

A string representing the new URL the window is navigating to.

`HashChangeEvent.oldURL` Read only

A string representing the previous URL from which the window was navigated.

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

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

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

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

```js
window.addEventListener(
  "hashchange",
  () => {
    console.log("The hash has changed!");
  },
  false,
);
```

Or use the `onhashchange` event handler property:

```js
function locationHashChanged() {
  if (location.hash === "#cool-feature") {
    console.log("You're visiting a cool feature!");
  }
}

window.onhashchange = locationHashChanged;
```

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

| Specification |
| --- |
| HTML Standard # event-hashchange |
| HTML Standard # handler-window-onhashchange |

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

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

See also
--------

* `popstate` event


Window: languagechange event - Web APIs

Window: languagechange event
============================

The **`languagechange`** event is fired at the global scope object when the user's preferred language changes.

Syntax
------

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

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

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

A generic `Event`.

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

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

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

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

```js
window.addEventListener("languagechange", () => {
  console.log("languagechange event detected!");
});
```

Or use the `onlanguagechange` event handler property:

```js
window.onlanguagechange = (event) => {
  console.log("languagechange event detected!");
};
```

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

| Specification |
| --- |
| HTML Standard # event-languagechange |
| HTML Standard # handler-window-onlanguagechange |

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

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

See also
--------

* `navigator.language`
* `navigator.languages`
* `navigator`


Window: dump() method - Web APIs

Window: dump() 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.dump()`** method logs messages to the browser's standard output (`stdout`). If the browser was started from a terminal, output sent to `dump()` will appear in the terminal.

Output from `dump()` is *not* sent to the browser's developer tools console. To log to the developer tools console, use `console.log()`.

Syntax
------

```js
dump(message)
```

### Parameters

`message`

A string containing the message to log.

### Return value

None (`undefined`).

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.


Window: locationbar property - Web APIs

Window: locationbar property
============================

Returns the `locationbar` 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-locationbar-dev |

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

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

See also
--------

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


Window: blur() method - Web APIs

Window: blur() method
=====================

Shifts focus away from the window.

Syntax
------

```js
blur()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
window.blur();
```

Notes
-----

 The window.blur() method is the programmatic equivalent of the user shifting focus away
 from the current window.

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

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

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

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


Window: print() method - Web APIs

Window: print() method
======================

Opens the print dialog to print the current document.

If the document is still loading when this function is called, then the document will finish loading before opening the print dialog.

This method will block while the print dialog is open.

Syntax
------

```js
print()
```

### Parameters

None.

### Return value

None (`undefined`).

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

| Specification |
| --- |
| HTML Standard # printing |

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

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

See also
--------

* Printing
* `beforeprint` event
* `afterprint` event


Window: length property - Web APIs

Window: length property
=======================

 Returns the number of frames (either `<frame>` or
 `<iframe>` elements) in the window.

Value
-----

A number.

Examples
--------

```js
if (window.length) {
  // this is a document with subframes
}
```

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

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

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

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


Window: innerHeight property - Web APIs

Window: innerHeight property
============================

 The read-only **`innerHeight`** property of the
 `Window` interface returns the interior height of the window in pixels,
 including the height of the horizontal scroll bar, if present.

 The value of `innerHeight` is taken from the height of the window's
 layout viewport. The width can be obtained using the
 `innerWidth` property.

Value
-----

 An integer value indicating the window's layout viewport height in pixels. The property
 is read only and has no default value.

 To change the width of the window, call one of its resize methods, such as
 `resizeTo()` or `resizeBy()`.

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

 To obtain the height of the window minus its horizontal scroll bar and any borders, use
 the root `<html>` element's `clientHeight` property instead.

 Both `innerHeight` and `innerWidth` are available on any window
 or any object that behaves like a window, such as a tab or frame.

Examples
--------

### Assuming a frameset

```js
console.log(window.innerHeight); // or

console.log(self.innerHeight);
// will log the height of the frame viewport within the frameset

console.log(parent.innerHeight);
// will log the height of the viewport of the closest frameset

console.log(top.innerHeight);
// will log the height of the viewport of the outermost frameset
```

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

 To get the outer height of a window, i.e. the height of the whole browser window, see
 `window.outerHeight`.

### Graphical example

 The following figure shows the difference between `outerHeight` and
 `innerHeight`.

![innerHeight vs. outerHeight illustration](/en-US/docs/Web/API/Window/innerHeight/firefoxinnervsouterheight2.png)

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-innerheight |

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

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

See also
--------

* `window.innerWidth`
* `window.outerHeight`
* `window.outerWidth`


Window: scrollMaxX property - Web APIs

Window: scrollMaxX property
===========================

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

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

Value
-----

A number.

Examples
--------

```js
// Scroll to right edge of the page
let maxX = window.scrollMaxX;

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

Notes
-----

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

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

This is not part of any specification.

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

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


Window: scroll() method - Web APIs

Window: scroll() method
=======================

 The **`Window.scroll()`** method scrolls the window to a
 particular place in the document.

Syntax
------

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

### Parameters

* `x-coord` is the pixel along the horizontal axis of the document that you
 want displayed in the upper left.
* `y-coord` is the pixel along the vertical axis of the document that you
 want displayed in the upper left.

- or -

`options`

A dictionary containing the following parameters:

`top`

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

`left`

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

`behavior`

Determines whether scrolling is instant or animates smoothly. This option is a string which must take one of the following values:

* `smooth`: scrolling should animate smoothly
* `instant`: scrolling should happen instantly in a single jump
* `auto`: scroll behavior is determined by the computed value of `scroll-behavior`

### Return value

None (`undefined`).

Examples
--------

```html
<!-- put the 100th vertical pixel at the top of the window -->

<button onclick="scroll(0, 100);">click to scroll to the 100th pixel</button>
```

Using `options`:

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

Notes
-----

`Window.scrollTo()` is effectively the same as this method. For relative
 scrolling, see `Window.scrollBy()`, `Window.scrollByLines()`,
 and `Window.scrollByPages()`.

 For scrolling elements, see `Element.scrollTop` and
 `Element.scrollLeft`.

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

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

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

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

See also
--------

* `Window.scrollByLines()`
* `Window.scrollByPages()`
* `Element.scrollIntoView()`


Window: sidebar property - Web APIs

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

**Warning:** This non-standard Firefox-only alias of the `window.external` property has been removed.

Returns a sidebar object which contains several methods for registering add-ons with the browser.

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

The sidebar object returned has the following methods:

| Method | Description (SeaMonkey) | Description (Firefox) |
| --- | --- | --- |
| `addPanel(title, contentURL, "")` | Adds a sidebar panel. |
 Obsolete since Firefox 23 (only present in SeaMonkey).End users
 can use the "load this bookmark in the sidebar" option instead. Also see
 Creating a Firefox sidebar. |
| `addPersistentPanel(title, contentURL, "")` | Adds a sidebar panel, which is able to work in the background. |
| `AddSearchProvider(*descriptionURL)*` |
 Dummy function; does nothing. See
 Autodiscovery of search plugins.
  |
| `addSearchEngine(engineURL, iconURL,
suggestedTitle, suggestedCategory)`

Deprecated
 |
 Installs a search engine (Sherlock).
 Adding Sherlock search engines contains more details.

**Note:** This was made obsolete in Firefox 44, and has
 been removed completely in Firefox 59.

 |
| `IsSearchProviderInstalled(*descriptionURL)*` | Indicates if a specific search provider (OpenSearch) is installed. |

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

Mozilla-specific. Not part of any standard.

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

 Removed in Firefox 102.
 For more information see Firefox compatibility information in `window.external`.


Window: closed property - Web APIs

Window: closed property
=======================

 The **`Window.closed`** read-only property indicates whether
 the referenced window is closed or not.

Value
-----

A boolean value. Possible values:

* `true`: The window has been closed.
* `false`: The window is open.
Examples
--------

### Change the URL of a window from a popup

 The following example demonstrates how a popup window can change the URL of the window
 that opened it. Before attempting to change the URL, it checks that the current window
 has an opener using the `window.opener` property and that the opener isn't
 closed:

```js
// Check that an opener exists and is not closed
if (window.opener && !window.opener.closed) {
  window.opener.location.href = "http://www.mozilla.org";
}
```

Note that popups can only access the window that opened them.

### Refreshing a previously opened popup

 In this example the function `refreshPopupWindow()` calls the
 `reload()` method of the popup's location object to refresh its data. If the
 popup hasn't been opened yet or the user has closed it a new window is opened.

```js
let popupWindow = null;

function refreshPopupWindow() {
  if (popupWindow && !popupWindow.closed) {
    // popupWindow is open, refresh it
    popupWindow.location.reload(true);
  } else {
    // Open a new popup window
    popupWindow = window.open("popup.html", "dataWindow");
  }
}
```

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

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

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

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


Window: personalbar property - Web APIs

Window: personalbar property
============================

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


Window: event property - Web APIs

Window: event 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 read-only `Window` property **`event`** returns the `Event` which is currently being handled by the site's code. Outside the context of an event handler, the value is always `undefined`.

You *should* avoid using this property in new code, and should instead use the `Event` passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.

**Note:** This property can be fragile, in that there may be situations in which the returned `Event` is not the expected value. In addition, `Window.event` is not accurate for events dispatched within shadow trees.

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

| Specification |
| --- |
| DOM Standard # dom-window-event |

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

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

See also
--------

* `Event.srcElement`


Window: cancelIdleCallback() method - Web APIs

Window: cancelIdleCallback() method
===================================

 The **`window.cancelIdleCallback()`** method cancels a callback
 previously scheduled with `window.requestIdleCallback()`.

Syntax
------

```js
cancelIdleCallback(handle)
```

### Parameters

`handle`

 The ID value returned by `window.requestIdleCallback()` when the
 callback was established.

### Return value

None (`undefined`).

Examples
--------

 See our complete example
 in the article Cooperative Scheduling of Background Tasks API.

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

| Specification |
| --- |
| requestIdleCallback() Cooperative Scheduling of Background Tasks # the-cancelidlecallback-method |

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

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


Window: vrdisplaydeactivate event - Web APIs

Window: vrdisplaydeactivate 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 **`vrdisplaydeactivate`** event of the WebVR API is fired when a VR display can no longer be presented to, for example if an HMD has gone into standby or sleep mode due to a period of inactivity.

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

onvrdisplaydeactivate = (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 `vrdisplaydeactivate` event in an `addEventListener` method:

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

Or use the `onvrdisplaydeactivate` event handler property:

```js
window.onvrdisplaydeactivate = () => {
  info.textContent = "Display deactivated.";
  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: mozInnerScreenX property - Web APIs

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

 Gets the X coordinate of the top-left corner of the window's viewport, in screen
 coordinates.

**Note:** This coordinate is reported in CSS pixels, not in hardware pixels. That means it can be affected by the zoom level; to compute the actual number of physical screen pixels, you should use the `nsIDOMWindowUtils.screenPixelsPerCSSPixel` property.

Value
-----

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

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

 Not part of any W3C technical
 specification or recommendation.

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

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

See also
--------

* `window.mozInnerScreenY`
* `nsIDOMWindowUtils.screenPixelsPerCSSPixel`


Window: rejectionhandled event - Web APIs

Window: rejectionhandled event
==============================

The **`rejectionhandled`** event is sent to the script's global scope (usually `window` but also `Worker`) whenever a rejected JavaScript `Promise` is handled late, i.e. when a handler is attached to the promise after its rejection had caused an `unhandledrejection` event.

This can be used in debugging and for general application resiliency, in tandem with the `unhandledrejection` event, which is sent when a promise is rejected but there is no handler for the rejection at the time.

Syntax
------

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

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

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

A `PromiseRejectionEvent`. Inherits from `Event`.

Event

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

`PromiseRejectionEvent.promise` Read only

The JavaScript `Promise` that was rejected.

`PromiseRejectionEvent.reason` Read only

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

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

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

* `HTMLBodyElement`
* `HTMLFrameSetElement`
* `SVGSVGElement`
Example
-------

You can use the `rejectionhandled` event to log promises that get rejected to the console, along with the reasons why they were rejected:

```js
window.addEventListener(
  "rejectionhandled",
  (event) => {
    console.log(`Promise rejected; reason: ${event.reason}`);
  },
  false,
);
```

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

| Specification |
| --- |
| HTML Standard # unhandled-promise-rejections |
| HTML Standard # handler-window-onrejectionhandled |

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

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

See also
--------

* Promise rejection events
* `PromiseRejectionEvent`
* `Promise`
* `unhandledrejection`


Window: pageshow event - Web APIs

Window: pageshow event
======================

The **`pageshow`** event is sent to a `Window` when the browser displays the window's document due to navigation.

This includes:

* Initially loading the page
* Navigating to the page from another page in the same window or tab
* Restoring a frozen page on mobile OSes
* Returning to the page using the browser's forward or back buttons

**Note:** During the initial page load, the `pageshow` event fires *after* the `load` event.

Syntax
------

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

```js
addEventListener("pageshow", (event) => {});
onpageshow = (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 `onpageshow` is also available on the following targets:

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

This example sets up event handlers for events listed in the array `events`. The handler, `eventLogger()`, logs the type of event that occurred to the console, and includes the value of the `persisted` flag on `pageshow` and `pagehide` events.

### JavaScript

```js
const events = ["pagehide", "pageshow", "unload", "load"];

const eventLogger = (event) => {
  switch (event.type) {
    case "pagehide":
    case "pageshow": {
      let isPersisted = event.persisted ? "persisted" : "not persisted";
      console.log(`Event: ${event.type} - ${isPersisted}`);
      break;
    }
    default:
      console.log(`Event: ${event.type}`);
      break;
  }
};

events.forEach((eventName) => window.addEventListener(eventName, eventLogger));
```

### HTML

```html
<p>
  Open the console and watch the output as you navigate to and from this page.
  Try loading new pages into this tab, then navigating forward and backward
  through history, noting the events' output to the log.
</p>
```

### Results

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

| Specification |
| --- |
| HTML Standard # event-pageshow |

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

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

See also
--------

* `pagehide`


Window: beforeunload event - Web APIs

Window: beforeunload event
==========================

The **`beforeunload`** event is fired when the current window, contained document, and associated resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.

The main use case for this event is to trigger a browser-generated confirmation dialog that asks users to confirm if they *really* want to leave the page when they try to close or reload it, or navigate somewhere else. This is intended to help prevent loss of unsaved data.

The dialog can be triggered in the following ways:

* Calling the event object's `preventDefault()` method.
* Setting the event object's `returnValue` property to a non-empty string value or any other truthy value.
* Returning any truthy value from the event handler function, e.g. `return "string"`. Note that this only works when the function is attached via the `onbeforeunload` property, not the `addEventListener()` method. This behavior is consistent across modern versions of Firefox, Safari, and Chrome.

The last two mechanisms are legacy features; best practice is to trigger the dialog by invoking `preventDefault()` on the event object, while also setting `returnValue` to support legacy cases.

Syntax
------

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

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

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

A `BeforeUnloadEvent`. Inherits from `Event`.

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

To trigger the dialog being shown when the user closes or navigates the tab, a `beforeunload` event handler function should call `preventDefault()` on the event object. You should note that modern implementations:

* Require sticky activation for the dialog to be displayed. In other words, the browser will only show the dialog box if the frame or any embedded frame receives a user gesture or user interaction. If the user has never interacted with the page, then there is no user data to save, so no legitimate use case for the dialog.
* Only show a generic browser-specified string in the displayed dialog. This cannot be controlled by the webpage code.

The `beforeunload` event suffers from some problems:

* It is not reliably fired, especially on mobile platforms. For example, the `beforeunload` 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.
**Note:** It is recommended to use the `visibilitychange` event as a more reliable signal for automatic app state saving that gets around problems like the above. See Don't lose user and app state, use Page Visibility for more details.
* In Firefox, `beforeunload` is not compatible with the back/forward cache (bfcache): that is, Firefox will not place pages in the bfcache if they have `beforeunload` listeners, and this is bad for performance.

It is therefore recommended that developers listen for `beforeunload` only when users have unsaved changes so that the dialog mentioned above can be used to warn them about impending data loss, and remove the listener again when it is not needed. Listening for `beforeunload` sparingly can minimize the effect on performance.

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

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

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

In the following example we have an HTML text `<input>` to represent some data that could be changed and require saving:

```html
<form>
  <input type="text" name="name" id="name" />
</form>
```

Our JavaScript attaches an `input` event listener to the `<input>` element that listens for changes in the inputted value. When the value is updated to a non-empty value, a `beforeunload` event listener is attached to the `Window` object.

If the value becomes an empty string again (i.e. the value is deleted), the `beforeunload` event listener is removed again — as mentioned above in the Usage notes, the listener should be removed when there is no unsaved data to warn about.

The `beforeunload` event handler function invokes `event.preventDefault()` to trigger the warning dialog when the user closes or navigates the tab. We have also included `event.returnValue = true` in the handler function so that any browsers that don't support the `event.preventDefault()` mechanism will still run the demo correctly.

```js
const beforeUnloadHandler = (event) => {
  // Recommended
  event.preventDefault();

  // Included for legacy support, e.g. Chrome/Edge < 119
  event.returnValue = true;
};

const nameInput = document.querySelector("#name");

nameInput.addEventListener("input", (event) => {
  if (event.target.value !== "") {
    window.addEventListener("beforeunload", beforeUnloadHandler);
  } else {
    window.removeEventListener("beforeunload", beforeUnloadHandler);
  }
});
```

When the `<input>` value is non-empty, if you try to close, navigate, or reload the page the browser displays the warning dialog. Try it out:

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

| Specification |
| --- |
| HTML Standard # event-beforeunload |
| HTML Standard # handler-window-onbeforeunload |

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

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

See also
--------

* `BeforeUnloadEvent` interface
* Related events:
    + `DOMContentLoaded`
    + `readystatechange`
    + `load`
    + `unload`
* Page Lifecycle API provides more useful guidance on handling page lifecycle behavior in your web apps.


Window: scrollX property - Web APIs

Window: scrollX property
========================

 The read-only **`scrollX`** property of the
 `Window` interface returns the number of pixels that the document is
 currently scrolled horizontally. This value is subpixel precise in modern browsers,
 meaning that it isn't necessarily a whole number. You can get the number of pixels the
 document is scrolled vertically from the `scrollY`
 property.

Value
-----

 In practice, the returned value is a double-precision floating-point value with the
 range of E(min)=-1022 to E(max)=1023 indicating the number of pixels the document is
 currently scrolled horizontally from the origin, where a positive value means the content
 is scrolled to the left. If the document is rendered on a subpixel-precise device, then
 the returned value is also subpixel-precise and may contain a decimal component. If the
 document isn't scrolled at all left or right, then `scrollX` is 0.

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

 In more technical terms, `scrollX` returns the X coordinate of the left edge
 of the current viewport. If there is no viewport, the returned value is
 0.

Examples
--------

 This example checks the current horizontal scroll position of the document. If it's
 greater than 400 pixels, the window is scrolled back to the beginning.

```js
if (window.scrollX > 400) {
  window.scroll(0, 0);
}
```

Notes
-----

The `pageXOffset` property is an alias for the `scrollX` property:

```js
window.pageXOffset === window.scrollX; // always true
```

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

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

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

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

See also
--------

* `Window.scrollY`


Window: navigation property - Web APIs

Window: navigation property
===========================

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

The **`navigation`** read-only property of the `Window` interface returns the current `window`'s associated `Navigation` object.

This is the entry point for the Navigation API.

Value
-----

A `Navigation` object instance.

Examples
--------

```js
let currentNavEntries = window.navigation.entries();
```

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

| Specification |
| --- |
| HTML Standard # dom-navigation |

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

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

See also
--------

* Modern client-side routing: the Navigation API
* Navigation API explainer
* Domenic Denicola's Navigation API live demo


Window: opener property - Web APIs

Window: opener property
=======================

 The `Window` interface's
 **`opener`** property returns a reference to the window that
 opened the window, either with `open()`, or by navigating
 a link with a `target` attribute.

 In other words, if window `A` opens window `B`,
 `B.opener` returns `A`.

Value
-----

 A `Window`-like object referring to the window that opened the current
 window (using `window.open()`, or by a link with `target` attribute set). If this window was not opened by being linked to or created by
 another, returns `null`.

 If the opener is not on the same origin as the current page, functionality of the
 opener object is limited. For example, variables and functions on the window object are
 not accessible. However, navigation of the opener window is possible, which means that
 the opened page can open a URL in the original tab or window. In some cases, this makes
 phishing attacks possible, where a trusted page that is opened in the original window is
 replaced by a phishing page by the newly opened page.

 In the following cases, the browser does not populate `window.opener`, but
 leaves it `null`:

* The opener can be omitted by specifying
 `rel=noopener` on a link, or passing
 `noopener` in the `windowFeatures` parameter.
* Windows opened because of links with a `target` of `_blank` don't get an `opener`, unless explicitly
 requested with `rel=opener`.
* Having a `Cross-Origin-Opener-Policy` header with a value of
 `same-origin` prevents setting `opener`. Since the new window is
 loaded in a different browsing context, it won't have a reference to the opening
 window.
Specifications
--------------

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

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

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


Window: parent property - Web APIs

Window: parent property
=======================

 The **`Window.parent`** property is a reference to the parent
 of the current window or subframe.

 If a window does not have a parent, its `parent` property is a reference to
 itself.

 When a window is loaded in an `<iframe>`, `<object>`, or
 `<frame>`, its parent is the window with the element embedding the
 window.

Value
-----

A `Window` or `<iframe>` object.

Examples
--------

```js
if (window.parent !== window.top) {
  // We're deeper than one down
}
```

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

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

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

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

See also
--------

* `window.frameElement` returns the specific element (such as
 `<iframe>`) the `window` is embedded into.
* `window.top` returns a reference to the top-level window.


Window: focus() method - Web APIs

Window: focus() method
======================

Makes a request to bring the window to the front. It may fail due to user settings and the window isn't guaranteed to be frontmost before this method returns.

Syntax
------

```js
focus()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

```js
if (clicked) {
  window.focus();
}
```

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

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

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

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


Window: outerHeight property - Web APIs

Window: outerHeight property
============================

The **`Window.outerHeight`** read-only property returns the height in pixels of the whole browser window, including any sidebar, 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 height of a window, i.e. the height of the page being displayed, see `window.innerHeight`.

### Graphical example

The following figure shows the difference between `outerHeight` and `innerHeight`.

![innerHeight vs. outerHeight illustration](/en-US/docs/Web/API/Window/outerHeight/firefoxinnervsouterheight2.png)

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

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

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

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

See also
--------

* `window.innerHeight`
* `window.innerWidth`
* `window.outerWidth`
* `window.resizeBy()`
* `window.resizeTo()`


Window: requestIdleCallback() method - Web APIs

Window: requestIdleCallback() method
====================================

 The **`window.requestIdleCallback()`** method queues a function
 to be called during a browser's idle periods. This enables developers to perform
 background and low priority work on the main event loop, without impacting
 latency-critical events such as animation and input response. Functions are generally
 called in first-in-first-out order; however, callbacks which have a `timeout`
 specified may be called out-of-order if necessary in order to run them before the
 timeout elapses.

 You can call `requestIdleCallback()` within an idle callback function to
 schedule another callback to take place no sooner than the next pass through the event
 loop.

**Note:** A `timeout` option is strongly recommended for required work,
 as otherwise it's possible multiple seconds will elapse before the callback is fired.

Syntax
------

```js
requestIdleCallback(callback)
requestIdleCallback(callback, options)
```

### Parameters

`callback`

 A reference to a function that should be called in the near future, when the event
 loop is idle. The callback function is passed an `IdleDeadline` object
 describing the amount of time available and whether or not the callback has been run
 because the timeout period expired.

`options` Optional

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

`timeout`

If the number of milliseconds represented by this parameter has elapsed and the callback has not already been called, then a task to execute the callback is queued in the event loop (even if doing so risks causing a negative performance impact). `timeout` must be a positive value or it is ignored.

### Return value

 An ID which can be used to cancel the callback by passing it into the
 `window.cancelIdleCallback()` method.

Examples
--------

 See our complete example
 in the article Cooperative Scheduling of Background Tasks API.

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

| Specification |
| --- |
| requestIdleCallback() Cooperative Scheduling of Background Tasks # the-requestidlecallback-method |

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

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

See also
--------

* `window.cancelIdleCallback()`
* `IdleDeadline`
* `setTimeout()`
* `setInterval()`
* `window.requestAnimationFrame`


Window: releaseEvents() method - Web APIs

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

Releases the window from trapping events of a specific type.

Syntax
------

```js
releaseEvents(eventType)
```

### Parameters

`eventType`

`eventType` is a combination of the following values:
 `Event.ABORT`, `Event.BLUR`, `Event.CLICK`,
 `Event.CHANGE`, `Event.DBLCLICK`, `Event.DRAGDDROP`,
 `Event.ERROR`, `Event.FOCUS`, `Event.KEYDOWN`,
 `Event.KEYPRESS`, `Event.KEYUP`, `Event.LOAD`,
 `Event.MOUSEDOWN`, `Event.MOUSEMOVE`, `Event.MOUSEOUT`,
 `Event.MOUSEOVER`, `Event.MOUSEUP`, `Event.MOVE`,
 `Event.RESET`, `Event.RESIZE`, `Event.SELECT`,
 `Event.SUBMIT`, `Event.UNLOAD`.

### Return value

None (`undefined`).

Examples
--------

```js
window.releaseEvents(Event.KEYPRESS);
```

Notes
-----

 Note that you can pass a list of events to this method using the following syntax:
 `window.releaseEvents(Event.KEYPRESS | Event.KEYDOWN | Event.KEYUP)`.

 See also `window.captureEvents`
 (
Deprecated
).

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

This is not part of any specification.

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

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


Window: message event - Web APIs

Window: message event
=====================

The `message` event is fired on a `Window` object when the window receives a message, for example from a call to `Window.postMessage()` from another browsing context.

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

onmessage = (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
--------

Suppose a script sends a message to a different browsing context, such as another `<iframe>`, using code like this:

```js
const targetFrame = window.top.frames[1];
const targetOrigin = "https://example.org";
const windowMessageButton = document.querySelector("#window-message");

windowMessageButton.addEventListener("click", () => {
  targetFrame.postMessage("hello there", targetOrigin);
});
```

The receiver can listen for the message using `addEventListener()` with code like this:

```js
window.addEventListener("message", (event) => {
  console.log(`Received message: ${event.data}`);
});
```

Alternatively the listener could use the `onmessage` event handler property:

```js
window.onmessage = (event) => {
  console.log(`Received message: ${event.data}`);
};
```

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

| Specification |
| --- |
| HTML Standard # event-message |
| HTML Standard # handler-window-onmessage |

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

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

See also
--------

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


Window: postMessage() method - Web APIs

Window: postMessage() method
============================

 The **`window.postMessage()`** method safely enables
 cross-origin communication between `Window` objects; *e.g.,* between
 a page and a pop-up that it spawned, or between a page and an iframe embedded within it.

 Normally, scripts on different pages are allowed to access each other if and only if
 the pages they originate from share the same protocol, port number, and host (also known
 as the "same-origin policy").
 `window.postMessage()` provides a controlled mechanism to securely circumvent this restriction (if used properly).

 Broadly, one window may obtain a reference to another (*e.g.,* via
 `targetWindow = window.opener`), and then dispatch a
 `MessageEvent` on it with `targetWindow.postMessage()`. The
 receiving window is then free to handle this event as needed. The arguments passed to `window.postMessage()`
 (*i.e.,* the "message") are exposed to the receiving window through the event object.

Syntax
------

```js
postMessage(message)
postMessage(message, options)
postMessage(message, targetOrigin)
postMessage(message, targetOrigin, transfer)
```

### Parameters

`message`

 Data to be sent to the other window. The data is serialized using
 the structured clone
 algorithm. This means you can pass a broad variety of data objects safely to the
 destination window without having to serialize them yourself.

`options` Optional

An optional object containing a `transfer` field with a sequence of transferable objects to transfer ownership of, and a optional `targetOrigin` field with a string which restricts the message to the limited targets only.

`targetOrigin` Optional

 Specifies what the origin of this window must be for the event to be
 dispatched, either as the literal string `"*"` (indicating no preference)
 or as a URI. If at the time the event is scheduled to be dispatched the scheme,
 hostname, or port of this window's document does not match that provided
 in `targetOrigin`, the event will not be dispatched; only if all three
 match will the event be dispatched. This mechanism provides control over where
 messages are sent; for example, if `postMessage()` was used to transmit a
 password, it would be absolutely critical that this argument be a URI whose origin is
 the same as the intended receiver of the message containing the password, to prevent
 interception of the password by a malicious third party. **Always provide a
specific `targetOrigin`, not `*`, if you know where the other
window's document should be located. Failing to provide a specific target discloses
the data you send to any interested malicious site.**

`transfer` Optional

 A sequence of transferable objects that are transferred with the message.
 The ownership of these objects is given to the destination side and they are no longer usable on the sending side.

### Return value

None (`undefined`).

The dispatched event
--------------------

 A `window` can listen for dispatched messages by executing the following
 JavaScript:

```js
window.addEventListener(
  "message",
  (event) => {
    if (event.origin !== "http://example.org:8080") return;

    // …
  },
  false,
);
```

The properties of the dispatched message are:

`data`

The object passed from the other window.

`origin`

 The origin of the window that sent the message at the time
 `postMessage` was called. This string is the concatenation of the protocol
 and "://", the host name if one exists, and ":" followed by a port number if a port is
 present and differs from the default port for the given protocol. Examples of typical
 origins are `https://example.org` (implying port
 `443`), `http://example.net` (implying port
 `80`), and `http://example.com:8080`. Note that
 this origin is *not* guaranteed to be the current or future origin of that
 window, which might have been navigated to a different location since
 `postMessage` was called.

`source`

 A reference to the `window` object that sent the message; you can use
 this to establish two-way communication between two windows with different origins.

Security concerns
-----------------

**If you do not expect to receive messages from other sites, *do not* add
any event listeners for `message` events.** This is a completely
 foolproof way to avoid security problems.

 If you do expect to receive messages from other sites, **always verify the
sender's identity** using the `origin` and possibly
 `source` properties. Any window (including, for example,
 `http://evil.example.com`) can send a message to any other window,
 and you have no guarantees that an unknown sender will not send malicious messages.
 Having verified identity, however, you still should **always verify the syntax of
the received message**. Otherwise, a security hole in the site you trusted to
 send only trusted messages could then open a cross-site scripting hole in your site.

**Always specify an exact target origin, not `*`, when you use
`postMessage` to send data to other windows.** A malicious site can
 change the location of the window without your knowledge, and therefore it can intercept
 the data sent using `postMessage`.

### Secure shared memory messaging

 If `postMessage()` throws when used with `SharedArrayBuffer`
 objects, you might need to make sure you cross-site isolated your site properly. Shared
 memory is gated behind two HTTP headers:

* `Cross-Origin-Opener-Policy` with `same-origin` as value
 (protects your origin from attackers)
* `Cross-Origin-Embedder-Policy` with `require-corp` or
 `credentialless` as value (protects victims from your origin)

```http
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
```

 To check if cross origin isolation has been successful, you can test against the
 `crossOriginIsolated`
 property available to window and worker contexts:

```js
const myWorker = new Worker("worker.js");

if (crossOriginIsolated) {
  const buffer = new SharedArrayBuffer(16);
  myWorker.postMessage(buffer);
} else {
  const buffer = new ArrayBuffer(16);
  myWorker.postMessage(buffer);
}
```

Examples
--------

```js
/\*
 \* In window A's scripts, with A being on http://example.com:8080:
 \*/

const popup = window.open(/\* popup details \*/);

// When the popup has fully loaded, if not blocked by a popup blocker:

// This does nothing, assuming the window hasn't changed its location.
popup.postMessage(
  "The user is 'bob' and the password is 'secret'",
  "https://secure.example.net",
);

// This will successfully queue a message to be sent to the popup, assuming
// the window hasn't changed its location.
popup.postMessage("hello there!", "http://example.com");

window.addEventListener(
  "message",
  (event) => {
    // Do we trust the sender of this message? (might be
    // different from what we originally opened, for example).
    if (event.origin !== "http://example.com") return;

    // event.source is popup
    // event.data is "hi there yourself! the secret response is: rheeeeet!"
  },
  false,
);
```

```js
/\*
 \* In the popup's scripts, running on http://example.com:
 \*/

// Called sometime after postMessage is called
window.addEventListener("message", (event) => {
  // Do we trust the sender of this message?
  if (event.origin !== "http://example.com:8080") return;

  // event.source is window.opener
  // event.data is "hello there!"

  // Assuming you've verified the origin of the received message (which
  // you must do in any case), a convenient idiom for replying to a
  // message is to call postMessage on event.source and provide
  // event.origin as the targetOrigin.
  event.source.postMessage(
    "hi there yourself! the secret response " + "is: rheeeeet!",
    event.origin,
  );
});
```

### Notes

 Any window may access this method on any other window, at any time, regardless of the
 location of the document in the window, to send it a message. Consequently, any event
 listener used to receive messages **must** first check the identity of the
 sender of the message, using the `origin` and possibly `source`
 properties. This cannot be overstated: **Failure to check the `origin`
and possibly `source` properties enables cross-site scripting
attacks.**

 As with any asynchronously-dispatched script (timeouts, user-generated events), it is
 not possible for the caller of `postMessage` to detect when an event handler
 listening for events sent by `postMessage` throws an exception.

 After `postMessage()` is called, the `MessageEvent` will be
 dispatched *only after all pending execution contexts have finished*.
 For example, if `postMessage()` is invoked in an event handler, that event
 handler will run to completion, as will any remaining handlers for that same event,
 before the `MessageEvent` is dispatched.

 The value of the `origin` property of the dispatched event is not affected
 by the current value of `document.domain` in the calling window.

 For IDN host names only, the value of the `origin` property is not
 consistently Unicode or punycode; for greatest compatibility check for both the IDN and
 punycode values when using this property if you expect messages from IDN sites. This
 value will eventually be consistently IDN, but for now you should handle both IDN and
 punycode forms.

 The value of the `origin` property when the sending window contains a
 `javascript:` or `data:` URL is the origin of the script that
 loaded the URL.

### Using window.postMessage in extensions
Non-standard

`window.postMessage` is available to JavaScript running in chrome code
 (e.g., in extensions and privileged code), but the `source` property of the
 dispatched event is always `null` as a security restriction. (The other
 properties have their expected values.)

 It is not possible for content or web context scripts to specify a
 `targetOrigin` to communicate directly with an extension (either the
 background script or a content script). Web or content scripts *can* use
 `window.postMessage` with a `targetOrigin` of `"*"` to
 broadcast to every listener, but this is discouraged, since an extension cannot be
 certain the origin of such messages, and other listeners (including those you do not
 control) can listen in.

 Content scripts should use `runtime.sendMessage` to communicate with
 the background script. Web context scripts can use custom events to communicate with
 content scripts (with randomly generated event names, if needed, to prevent snooping
 from the guest page).

 Lastly, posting a message to a page at a `file:` URL currently requires that
 the `targetOrigin` argument be `"*"`. `file://` cannot
 be used as a security restriction; this restriction may be modified in the future.

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

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

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

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

See also
--------

* `Document.domain`
* `CustomEvent`
* `BroadcastChannel` - For same-origin communication.


Window: back() method - Web APIs

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

 The obsolete and non-standard method `back()` on the `window`
 interface returns the window to the previous item in the history. This was a
 Firefox-specific method and was removed in Firefox 31.

**Note:** Use the standard `history.back` method instead.

Syntax
------

```js
back()
```

### Parameters

None.

### Return value

None (`undefined`).

Examples
--------

This simple example handles a click on a "Back" button by calling `back()`.

```js
function handleMyBackButton() {
  if (canGoBack) {
    window.back();
  }
}
```

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