repo_id
stringlengths
22
103
file_path
stringlengths
41
147
content
stringlengths
181
193k
__index_level_0__
int64
0
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/dump/index.md
--- title: "Window: dump() method" short-title: dump() slug: Web/API/Window/dump page-type: web-api-instance-method status: - non-standard browser-compat: api.Window.dump --- {{ ApiRef() }} {{Non-standard_header}} 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()`](/en-US/docs/Web/API/console/log_static). ## Syntax ```js-nolint dump(message) ``` ### Parameters - `message` - : A string containing the message to log. ### Return value None ({{jsxref("undefined")}}). ## Specifications This feature is not part of any specification. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/external/index.md
--- title: "Window: external property" short-title: external slug: Web/API/Window/external page-type: web-api-instance-property status: - deprecated browser-compat: api.Window.external --- {{APIRef}} {{deprecated_header}} The `external` property of the {{domxref("Window")}} API returns an instance of the `External` interface, which was intended to contain functions related to adding external search providers to the browser. However, this is now deprecated, and the contained methods are now dummy functions that do nothing as per spec. ## Instance methods The `External` object has the following methods: <table class="fullwidth-table"> <tbody> <tr> <th>Method</th> <th>Description</th> </tr> <tr> <td> <code>AddSearchProvider(<em>descriptionURL)</em></code> </td> <td> Dummy function; does nothing. See <a href="/en-US/docs/Web/OpenSearch#autodiscovery_of_search_plugins" >Autodiscovery of search plugins</a >. </td> </tr> <tr> <td><code>IsSearchProviderInstalled()</code></td> <td>Dummy function; does nothing.</td> </tr> </tbody> </table> ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/resizeby/index.md
--- title: "Window: resizeBy() method" short-title: resizeBy() slug: Web/API/Window/resizeBy page-type: web-api-instance-method browser-compat: api.Window.resizeBy --- {{APIRef}} The **`Window.resizeBy()`** method resizes the current window by a specified amount. ## Syntax ```js-nolint resizeBy(xDelta, yDelta) ``` ### Parameters - `xDelta` is the number of pixels to grow the window horizontally. - `yDelta` is the number of pixels to grow the window vertically. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js // Shrink the window window.resizeBy(-200, -200); ``` ## Notes This method resizes the window relative to its current size. To resize the window in absolute terms, use {{domxref("window.resizeTo()")}}. ### Creating and resizing an external window For security reasons, it's no longer possible in Firefox for a website to change the default size of a window in a browser if the window wasn't created by `window.open()`, or contains more than one tab. See the compatibility table for details on the change. Even if you create window by `window.open()` **it is not resizable by default.** To make the window resizable, you must open it with the `"resizable"` feature. ```js // Create resizable window myExternalWindow = window.open( "https://example.com", "myWindowName", "resizable", ); // Resize window to 500x500 myExternalWindow.resizeTo(500, 500); // Make window relatively smaller to 400x400 myExternalWindow.resizeBy(-100, -100); ``` The window you create must respect the Same Origin Policy. If the window you open is not in the same origin as the current window, you will not be able to resize, or access any information on, that window/tab. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/credentialless/index.md
--- title: "Window: credentialless property" short-title: credentialless slug: Web/API/Window/credentialless page-type: web-api-instance-property status: - experimental browser-compat: api.Window.credentialless --- {{APIRef}}{{SeeCompatTable}} The **`window.credentialless`** read-only property returns a boolean that indicates whether the current document was loaded inside a credentialless {{htmlelement("iframe")}}, meaning that it is loaded in a new, ephemeral context. This context doesn't have access to the network, cookies, and storage data associated with its origin. It uses a new context local to the top-level document lifetime. In return, the {{httpheader("Cross-Origin-Embedder-Policy")}} (COEP) embedding rules can be lifted, so documents with COEP set can embed third-party documents that do not. See [IFrame credentialless](/en-US/docs/Web/Security/IFrame_credentialless) for a deeper explanation. ## Value A boolean. A value of `true` indicates that the document was loaded inside a credentialless `<iframe>`; `false` indicates that it was not. ## Examples You can specify a credentialless `<iframe>` like so: ```html <iframe src="https://en.wikipedia.org/wiki/Spectre_(security_vulnerability)" title="Spectre vulnerability Wikipedia page" width="960" height="600" credentialless></iframe> ``` In supporting browsers, if the document loaded in the `<iframe>` were to run the following line, it would return `true`: ```js console.log(window.credentialless); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/copy_event/index.md
--- title: "Window: copy event" short-title: copy slug: Web/API/Window/copy_event page-type: web-api-event browser-compat: api.Element.copy_event --- {{APIRef}} The **`copy`** event fires when the user initiates a copy action through the browser's user interface. The original target for this event is the {{domxref("Element")}} that was the intended target of the copy action. You can listen for this event on the {{domxref("Window")}} interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the [Element: copy event](/en-US/docs/Web/API/Element/copy_event). ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("copy", (event) => {}); oncopy = (event) => {}; ``` ## Event type A {{domxref("ClipboardEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ClipboardEvent")}} ## Examples ```js window.addEventListener("copy", (event) => { console.log("copy action initiated"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("Window/cut_event", "cut")}}, {{domxref("Window/paste_event", "paste")}} - This event on {{domxref("Element")}} targets: {{domxref("Element/copy_event", "copy")}} - This event on {{domxref("Document")}} targets: {{domxref("Document/copy_event", "copy")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/document/index.md
--- title: "Window: document property" short-title: document slug: Web/API/Window/document page-type: web-api-instance-property browser-compat: api.Window.document --- {{APIRef}} **`window.document`** returns a reference to the [document](/en-US/docs/Web/API/Document) contained in the window. ## Value A [document](/en-US/docs/Web/API/Document) object. ## Examples ```js console.log(window.document.title); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/online_event/index.md
--- title: "Window: online event" short-title: online slug: Web/API/Window/online_event page-type: web-api-event browser-compat: api.Window.online_event --- {{APIRef}} The **`online`** event of the {{domxref("Window")}} interface is fired when the browser has gained access to the network and the value of {{domxref("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 {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("online", (event) => {}); ononline = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Event handler aliases In addition to the `Window` interface, the event handler property `ononline` is also available on the following targets: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`offline`](/en-US/docs/Web/API/Window/offline_event)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/beforeprint_event/index.md
--- title: "Window: beforeprint event" short-title: beforeprint slug: Web/API/Window/beforeprint_event page-type: web-api-event browser-compat: api.Window.beforeprint_event --- {{APIRef}} The **`beforeprint`** event is fired when the associated document is about to be printed or previewed for printing. The {{domxref("Window.afterprint_event", "afterprint")}} and `beforeprint` events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed. In general, you should prefer the use of a [`@media print`](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries#targeting_media_types) CSS at-rule, but it may be necessary to use these events in some cases. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("beforeprint", (event) => {}); onbeforeprint = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples Using `addEventListener()`: ```js window.addEventListener("beforeprint", (event) => { console.log("Before print"); }); ``` Using the `onbeforeprint` event handler property: ```js window.onbeforeprint = (event) => { console.log("Before print"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("Window/afterprint_event", "afterprint")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/frames/index.md
--- title: "Window: frames property" short-title: frames slug: Web/API/Window/frames page-type: web-api-instance-property browser-compat: api.Window.frames --- {{APIRef("DOM")}} Returns the window itself, which is an array-like object, listing the direct sub-frames of the current window. ## Value A list of frame objects. It is similar to an array in that it has a `length` property and its items can be accessed using the `[i]` notation. - `frameList === window` evaluates to true. - Each item in the `window.frames` pseudo-array represents the {{domxref("Window")}} object corresponding to the given {{HTMLElement("frame")}}'s or {{HTMLElement("iframe")}}'s content, not the `frame` or `iframe` DOM element (i.e., `window.frames[0]` is the same thing as `document.getElementsByTagName("iframe")[0].contentWindow`). - For more details about the returned value, refer to this [thread on mozilla.dev.platform](https://groups.google.com/d/topic/mozilla.dev.platform/VijG80aFnU8?hl=en&pli=1). ## Examples ```js const frames = window.frames; // or const frames = window.parent.frames; for (let i = 0; i < frames.length; i++) { // do something with each subframe as frames[i] frames[i].document.body.style.background = "red"; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/stop/index.md
--- title: "Window: stop() method" short-title: stop() slug: Web/API/Window/stop page-type: web-api-instance-method browser-compat: api.Window.stop --- {{APIRef}} The **`window.stop()`** stops further resource loading in the current browsing context, equivalent to the stop button in the browser. Because of how scripts are executed, this method cannot interrupt its parent document's loading, but it will stop its images, new windows, and other still-loading objects. ## Syntax ```js-nolint stop() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js window.stop(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/languagechange_event/index.md
--- title: "Window: languagechange event" short-title: languagechange slug: Web/API/Window/languagechange_event page-type: web-api-event browser-compat: api.Window.languagechange_event --- {{APIRef}} 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 {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("languagechange", (event) => {}); onlanguagechange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Event handler aliases In addition to the `Window` interface, the event handler property `onlanguagechange` is also available on the following targets: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("SVGSVGElement")}} ## Examples You can use the `languagechange` event in an {{domxref("EventTarget/addEventListener", "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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("navigator.language")}} - {{domxref("navigator.languages")}} - {{domxref("navigator")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/localstorage/index.md
--- title: "Window: localStorage property" short-title: localStorage slug: Web/API/Window/localStorage page-type: web-api-instance-property browser-compat: api.Window.localStorage --- {{APIRef("Web Storage API")}} The **`localStorage`** read-only property of the {{domxref("window")}} interface allows you to access a {{DOMxRef("Storage")}} object for the {{DOMxRef("Document")}}'s {{glossary("origin")}}; the stored data is saved across browser sessions. `localStorage` is similar to {{DOMxRef("Window.sessionStorage", "sessionStorage")}}, except that while `localStorage` data has no expiration time, `sessionStorage` data gets cleared when the page session ends — that is, when the page is closed. (`localStorage` data for a document loaded in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.) ## Value A {{DOMxRef("Storage")}} object which can be used to access the current origin's local storage space. ### Exceptions - `SecurityError` - : Thrown in one of the following cases: - The origin is not [a valid scheme/host/port tuple](/en-US/docs/Web/Security/Same-origin_policy#definition_of_an_origin). This can happen if the origin uses the `file:` or `data:` schemes, for example. - The request violates a policy decision. For example, the user has configured the browsers to prevent the page from persisting data. Note that if the user blocks cookies, browsers will probably interpret this as an instruction to prevent the page from persisting data. ## Description The keys and the values stored with `localStorage` are _always_ in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings. `localStorage` data **is specific to the protocol of the document**. In particular, for a site loaded over HTTP (e.g., `http://example.com`), `localStorage` returns a different object than `localStorage` for the corresponding site loaded over HTTPS (e.g., `https://example.com`). For documents loaded from `file:` URLs (that is, files opened in the browser directly from the user's local filesystem, rather than being served from a web server) the requirements for `localStorage` behavior are undefined and may vary among different browsers. In all current browsers, `localStorage` seems to return a different object for each `file:` URL. In other words, each `file:` URL seems to have its own unique local-storage area. But there are no guarantees about that behavior, so you shouldn't rely on it because, as mentioned above, the requirements for `file:` URLs remain undefined. So it's possible that browsers may change their `file:` URL handling for `localStorage` at any time. In fact some browsers _have_ changed their handling for it over time. ## Examples The following snippet accesses the current domain's local {{DOMxRef("Storage")}} object and adds a data item to it using {{DOMxRef("Storage.setItem()")}}. ```js localStorage.setItem("myCat", "Tom"); ``` The syntax for reading the `localStorage` item is as follows: ```js const cat = localStorage.getItem("myCat"); ``` The syntax for removing the `localStorage` item is as follows: ```js localStorage.removeItem("myCat"); ``` The syntax for removing all the `localStorage` items is as follows: ```js localStorage.clear(); ``` > **Note:** Please refer to the [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API) article for a full example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API) - {{DOMxRef("Window.sessionStorage")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/moveto/index.md
--- title: "Window: moveTo() method" short-title: moveTo() slug: Web/API/Window/moveTo page-type: web-api-instance-method browser-compat: api.Window.moveTo --- {{APIRef}} The **`moveTo()`** method of the {{domxref("Window")}} interface moves the current window to the specified coordinates. > **Note:** This function moves the window to an absolute location. In > contrast, {{domxref("window.moveBy()")}} moves the window relative to its current > location. ## Syntax ```js-nolint moveTo(x, y) ``` ### Parameters - `x` is the horizontal coordinate to be moved to. - `y` is the vertical coordinate to be moved to. ### Return value None ({{jsxref("undefined")}}). ## Examples This example moves the window to the top-left corner of the screen. ```js function origin() { window.moveTo(0, 0); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} As of Firefox 7, websites can no longer move a browser window [in the following cases](https://bugzil.la/565541#c24): 1. You can't move a window or tab that wasn't created by {{domxref("Window.open()")}}. 2. You can't move a window or tab when it's in a window with more than one tab. ## See also - {{domxref("Window.moveBy()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/messageerror_event/index.md
--- title: "Window: messageerror event" short-title: messageerror slug: Web/API/Window/messageerror_event page-type: web-api-event browser-compat: api.Window.messageerror_event --- {{APIRef}} The `messageerror` event is fired on a {{domxref('Window')}} object when it receives a message that can't be deserialized. This event is not cancellable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("messageerror", (event) => {}); onmessageerror = (event) => {}; ``` ## Event type A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("MessageEvent")}} ## Event properties _This interface also inherits properties from its parent, {{domxref("Event")}}._ - {{domxref("MessageEvent.data")}} {{ReadOnlyInline}} - : The data sent by the message emitter. - {{domxref("MessageEvent.origin")}} {{ReadOnlyInline}} - : A string representing the origin of the message emitter. - {{domxref("MessageEvent.lastEventId")}} {{ReadOnlyInline}} - : A string representing a unique ID for the event. - {{domxref("MessageEvent.source")}} {{ReadOnlyInline}} - : A `MessageEventSource` (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter. - {{domxref("MessageEvent.ports")}} {{ReadOnlyInline}} - : An array of {{domxref("MessagePort")}} objects representing the ports associated with the channel the message is being sent through (where appropriate, e.g. in channel messaging or when sending a message to a shared worker). ## Examples Listen for `messageerror` using {{domxref("EventTarget/addEventListener", "addEventListener()")}}: ```js window.addEventListener("messageerror", (event) => { console.error(event); }); ``` The same, but using the `onmessageerror` event handler property: ```js window.onmessageerror = (event) => { console.error(event); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window.postMessage()")}} - Related events: {{domxref("Window/message_event", "message")}}.
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/parent/index.md
--- title: "Window: parent property" short-title: parent slug: Web/API/Window/parent page-type: web-api-instance-property browser-compat: api.Window.parent --- {{APIRef}} 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 {{htmlelement("iframe")}}, {{htmlelement("object")}}, or {{htmlelement("frame")}}, its parent is the window with the element embedding the window. ## Value A `Window` or {{htmlelement("iframe")}} object. ## Examples ```js if (window.parent !== window.top) { // We're deeper than one down } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.frameElement")}} returns the specific element (such as `<iframe>`) the `window` is embedded into. - {{domxref("window.top")}} returns a reference to the top-level window.
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/vrdisplaydisconnect_event/index.md
--- title: "Window: vrdisplaydisconnect event" short-title: vrdisplaydisconnect slug: Web/API/Window/vrdisplaydisconnect_event page-type: web-api-event status: - deprecated - non-standard browser-compat: api.Window.vrdisplaydisconnect_event --- {{APIRef("Window")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`vrdisplaydisconnect`** event of the [WebVR API](/en-US/docs/Web/API/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 {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("vrdisplaydisconnect", (event) => {}); onvrdisplaydisconnect = (event) => {}; ``` ## Event type A {{domxref("VRDisplayEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("VRDisplayEvent")}} ## Event properties _`VRDisplayEvent` also inherits properties from its parent object, {{domxref("Event")}}._ - {{domxref("VRDisplayEvent.display")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : The {{domxref("VRDisplay")}} associated with this event. - {{domxref("VRDisplayEvent.reason")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : A human-readable reason why the event was fired. ## Examples You can use the `vrdisplaydisconnect` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: > **Note:** This event was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). ```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](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard. Until all browsers have implemented the new [WebXR Device API](https://immersive-web.github.io/webxr/), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/). ## Browser compatibility {{Compat}} ## See also - [WebVR API](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/mozinnerscreeny/index.md
--- title: "Window: mozInnerScreenY property" short-title: mozInnerScreenY slug: Web/API/Window/mozInnerScreenY page-type: web-api-instance-property status: - non-standard browser-compat: api.Window.mozInnerScreenY --- {{APIRef}}{{Non-standard_Header}} The `mozInnerScreenY` property of the {{domxref("Window")}} interface returns the Y coordinate of the top-left corner of the window's viewport, in screen coordinates. > **Note:** This coordinate is reported in CSS pixels, not in hardware pixels. ## Value The `window.mozInnerScreenY` property is a floating point, read-only value; it has no default value. ## Specifications This feature is not part of any current specification. It is not on track to become a standard. ## Browser compatibility {{Compat}} ## See also - {{domxref("window.mozInnerScreenX")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/deviceorientation_event/index.md
--- title: "Window: deviceorientation event" short-title: deviceorientation slug: Web/API/Window/deviceorientation_event page-type: web-api-event browser-compat: api.Window.deviceorientation_event --- {{APIRef("Device Orientation Events")}}{{securecontext_header}} The **`deviceorientation`** event is fired when fresh data is available from an orientation sensor about the current orientation of the device as compared to the Earth coordinate frame. This data is gathered from a magnetometer inside the device. See [Orientation and motion data explained](/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained) for details. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("deviceorientation", (event) => {}); ondeviceorientation = (event) => {}; ``` ## Event type A {{domxref("DeviceOrientationEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("DeviceOrientationEvent")}} ## Event properties - {{domxref("DeviceOrientationEvent.absolute")}} {{ReadOnlyInline}} - : A boolean that indicates whether the device is providing orientation data absolutely. - {{domxref("DeviceOrientationEvent.alpha")}} {{ReadOnlyInline}} - : A number representing the motion of the device around the z axis, express in degrees with values ranging from 0 (inclusive) to 360 (exclusive). - {{domxref("DeviceOrientationEvent.beta")}} {{ReadOnlyInline}} - : A number representing the motion of the device around the x axis, expressed in degrees with values ranging from -180 (inclusive) to 180 (exclusive). This represents the front to back motion of the device. - {{domxref("DeviceOrientationEvent.gamma")}} {{ReadOnlyInline}} - : A number representing the motion of the device around the y axis, expressed in degrees with values ranging from -90 (inclusive) to 90 (exclusive). This represents the left to right motion of the device. - `DeviceOrientationEvent.webkitCompassHeading` {{Non-Standard_Inline}} {{ReadOnlyInline}} - : A number represents the difference between the motion of the device around the z axis of the world system and the direction of the north, expressed in degrees with values ranging from 0 to 360. - `DeviceOrientationEvent.webkitCompassAccuracy` {{Non-Standard_Inline}} {{ReadOnlyInline}} - : The accuracy of the compass given as a positive or negative deviation. It's usually 10. ## Examples ```js if (window.DeviceOrientationEvent) { window.addEventListener( "deviceorientation", (event) => { const rotateDegrees = event.alpha; // alpha: rotation around z-axis const leftToRight = event.gamma; // gamma: left to right const frontToBack = event.beta; // beta: front back motion handleOrientationEvent(frontToBack, leftToRight, rotateDegrees); }, true, ); } const handleOrientationEvent = (frontToBack, leftToRight, rotateDegrees) => { // do something amazing }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`devicemotion`](/en-US/docs/Web/API/Window/devicemotion_event) - [Detecting device orientation](/en-US/docs/Web/API/Device_orientation_events/Detecting_device_orientation) - [Orientation and motion data explained](/en-US/docs/Web/API/Device_orientation_events/Orientation_and_motion_data_explained)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/length/index.md
--- title: "Window: length property" short-title: length slug: Web/API/Window/length page-type: web-api-instance-property browser-compat: api.Window.length --- {{ ApiRef() }} Returns the number of frames (either {{HTMLElement("frame")}} or {{HTMLElement("iframe")}} elements) in the window. ## Value A number. ## Examples ```js if (window.length) { // this is a document with subframes } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/documentpictureinpicture/index.md
--- title: "Window: documentPictureInPicture property" short-title: documentPictureInPicture slug: Web/API/Window/documentPictureInPicture page-type: web-api-instance-property status: - experimental browser-compat: api.Window.documentPictureInPicture --- {{APIRef}}{{seecompattable}}{{SecureContext_Header}} The **`documentPictureInPicture`** read-only property of the {{domxref("Window")}} interface returns a reference to the {{domxref("DocumentPictureInPicture")}} object for the current document context. ## Value A {{domxref("DocumentPictureInPicture")}} object instance. ## Examples ```js const videoPlayer = document.getElementById("player"); // ... // Open a Picture-in-Picture window. await window.documentPictureInPicture.requestWindow({ width: videoPlayer.clientWidth, height: videoPlayer.clientHeight, }); // ... ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Document Picture-in-Picture API", "Document Picture-in-Picture API", "", "nocode")}} - [Using the Document Picture-in-Picture API](/en-US/docs/Web/API/Document_Picture-in-Picture_API/Using)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/releaseevents/index.md
--- title: "Window: releaseEvents() method" short-title: releaseEvents() slug: Web/API/Window/releaseEvents page-type: web-api-instance-method status: - deprecated browser-compat: api.Window.releaseEvents --- {{APIRef}}{{Deprecated_Header}} Releases the window from trapping events of a specific type. ## Syntax ```js-nolint 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 ({{jsxref("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`](/en-US/docs/Web/API/Window/captureEvents) ({{Deprecated_Inline}}). ## Specifications This is not part of any specification. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/prompt/index.md
--- title: "Window: prompt() method" short-title: prompt() slug: Web/API/Window/prompt page-type: web-api-instance-method browser-compat: api.Window.prompt --- {{ApiRef("Window")}} `window.prompt()` instructs the browser to display a dialog with an optional message prompting the user to input some text, and to wait until the user either submits the text or cancels the dialog. Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to submit text or to cancel the dialog. ## Syntax ```js-nolint prompt() prompt(message) prompt(message, defaultValue) ``` ### Parameters - `message` {{optional_inline}} - : A string of text to display to the user. Can be omitted if there is nothing to show in the prompt window. - `defaultValue` {{optional_inline}} - : A string containing the default value displayed in the text input field. ### Return value A string containing the text entered by the user, or `null`. ## Examples ```js let sign = prompt("What's your sign?"); if (sign.toLowerCase() === "scorpio") { alert("Wow! I'm a Scorpio too!"); } // there are many ways to use the prompt feature sign = window.prompt(); // open the blank prompt window sign = prompt(); // open the blank prompt window sign = window.prompt("Are you feeling lucky"); // open the window with Text "Are you feeling lucky" sign = window.prompt("Are you feeling lucky", "sure"); // open the window with Text "Are you feeling lucky" and default value "sure" ``` When the user clicks the OK button, text entered in the input field is returned. If the user clicks OK without entering any text, an empty string is returned. If the user clicks the Cancel button, this function returns `null`. The above prompt appears as follows (in Chrome on macOS): [![prompt() dialog in Chrome on macOS](prompt.png)](prompt.png) ## Notes A prompt dialog contains a single-line textbox, a Cancel button, and an OK button, and returns the (possibly empty) text the user entered into that textbox. Please note that result is a string. That means you should sometimes cast the value given by the user. For example, if their answer should be a Number, you should cast the value to Number. ```js const aNumber = Number(window.prompt("Type a number", "")); ``` Dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window). Alternatively {{HTMLElement("dialog")}} element can be used to take user inputs. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("dialog")}} element - {{domxref("window.alert", "alert")}} - {{domxref("window.confirm", "confirm")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/fullscreen/index.md
--- title: "Window: fullScreen property" short-title: fullScreen slug: Web/API/Window/fullScreen page-type: web-api-instance-property status: - non-standard browser-compat: api.Window.fullScreen --- {{APIRef}}{{Non-standard_Header}} The **`fullScreen`** property of the `Window` interface indicates whether the window is displayed in full screen mode or not. ## Value A boolean value with `true` meaning that the window is in full-screen mode and `false` meaning it isn't. ## Notes - Switching between regular window and full screen will fire the "resize" event on the corresponding window. ## Examples ```js if (window.fullScreen) { // it's fullscreen! } else { // not fullscreen! } ``` ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/find/index.md
--- title: "Window: find() method" short-title: find() slug: Web/API/Window/find page-type: web-api-instance-method status: - non-standard browser-compat: api.Window.find --- {{ApiRef}}{{Non-standard_Header}} > **Note:** Support for `Window.find()` might change in future > versions of Gecko. See [Firefox bug 672395](https://bugzil.la/672395). The **`Window.find()`** method finds a string in a window sequentially. ## Syntax ```js-nolint find(aString, aCaseSensitive, aBackwards, aWrapAround, aWholeWord, aSearchInFrames, aShowDialog) ``` ### Parameters - `aString` - : The text string for which to search. - `aCaseSensitive` - : A boolean value. If `true`, specifies a case-sensitive search. - `aBackwards` - : A boolean value. If `true`, specifies a backward search. - `aWrapAround` - : A boolean value. If `true`, specifies a wrap around search. - `aWholeWord` - : A boolean value. If `true`, specifies a whole word search. - `aSearchInFrames` - : A boolean value. If `true`, specifies a search in frames. - `aShowDialog` - : A boolean value. If `true`, a search dialog is shown. ### Return value `true` if the string is found; otherwise, `false`. ## Examples ### JavaScript ```js function findString(text) { document.querySelector("#output").textContent = `String found? ${window.find( text, )}`; } ``` ### HTML ```html <p>Apples, Bananas, and Oranges.</p> <button type="button" onClick='findString("Apples")'>Search for Apples</button> <button type="button" onClick='findString("Bananas")'> Search for Bananas </button> <button type="button" onClick='findString("Orange")'>Search for Orange</button> <p id="output"></p> ``` ### Result {{EmbedLiveSample("Examples")}} ## Notes In some browsers, `Window.find()` selects (highlights) the found content on the site. ## Specifications This is not part of any specification. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/outerheight/index.md
--- title: "Window: outerHeight property" short-title: outerHeight slug: Web/API/Window/outerHeight page-type: web-api-instance-property browser-compat: api.Window.outerHeight --- {{APIRef}} 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 {{domxref("window.resizeBy()")}} and {{domxref("window.resizeTo()")}}. To get the inner height of a window, i.e. the height of the page being displayed, see {{domxref("window.innerHeight")}}. ### Graphical example The following figure shows the difference between `outerHeight` and `innerHeight`. ![innerHeight vs. outerHeight illustration](firefoxinnervsouterheight2.png) ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.innerHeight")}} - {{domxref("window.innerWidth")}} - {{domxref("window.outerWidth")}} - {{domxref("window.resizeBy()")}} - {{domxref("window.resizeTo()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/unhandledrejection_event/index.md
--- title: "Window: unhandledrejection event" short-title: unhandledrejection slug: Web/API/Window/unhandledrejection_event page-type: web-api-event browser-compat: api.Window.unhandledrejection_event --- {{APIRef("HTML DOM")}} The **`unhandledrejection`** event is sent to the global scope of a script when a JavaScript {{jsxref("Promise")}} that has no rejection handler is rejected; typically, this is the {{domxref("window")}}, but may also be a {{domxref("Worker")}}. This is useful for debugging and for providing fallback error handling for unexpected situations. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("unhandledrejection", (event) => {}); onunhandledrejection = (event) => {}; ``` ## Event type A {{domxref("PromiseRejectionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PromiseRejectionEvent")}} ## Event properties - {{domxref("PromiseRejectionEvent.promise")}} {{ReadOnlyInline}} - : The JavaScript {{jsxref("Promise")}} that was rejected. - {{domxref("PromiseRejectionEvent.reason")}} {{ReadOnlyInline}} - : A value or {{jsxref("Object")}} indicating why the promise was rejected, as passed to {{jsxref("Promise.reject()")}}. ## Event handler aliases In addition to the `Window` interface, the event handler property `onunhandledrejection` is also available on the following targets: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("SVGSVGElement")}} ## Usage notes Allowing the `unhandledrejection` event to bubble will eventually result in an error message being output to the console. You can prevent this by calling {{domxref("Event.preventDefault", "preventDefault()")}} on the {{domxref("PromiseRejectionEvent")}}; see [Preventing default handling](#preventing_default_handling) below for an example. Because this event can leak data, {{jsxref("Promise")}} rejections that originate from a cross-origin script won't fire this event. ## Examples ### Basic error logging This example logs information about the unhandled promise rejection to the console. ```js window.addEventListener("unhandledrejection", (event) => { console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`); }); ``` You can also use the `onunhandledrejection` event handler property to set up the event listener: ```js window.onunhandledrejection = (event) => { console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`); }; ``` ### Preventing default handling Many environments (such as {{Glossary("Node.js")}}) report unhandled promise rejections to the console by default. You can prevent that from happening by adding a handler for `unhandledrejection` events that—in addition to any other tasks you wish to perform—calls {{domxref("Event.preventDefault()", "preventDefault()")}} to cancel the event, preventing it from bubbling up to be handled by the runtime's logging code. This works because `unhandledrejection` is cancelable. ```js window.addEventListener("unhandledrejection", (event) => { // code for handling the unhandled rejection // … // Prevent the default handling (such as outputting the // error to the console) event.preventDefault(); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Promise rejection events](/en-US/docs/Web/JavaScript/Guide/Using_promises#promise_rejection_events) - {{domxref("Window/rejectionhandled_event", "rejectionhandled")}} event - {{jsxref("Promise")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/offline_event/index.md
--- title: "Window: offline event" short-title: offline slug: Web/API/Window/offline_event page-type: web-api-event browser-compat: api.Window.offline_event --- {{APIRef}} The **`offline`** event of the {{domxref("Window")}} interface is fired when the browser has lost access to the network and the value of {{domxref("Navigator.onLine")}} switches to `false`. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("offline", (event) => {}); onoffline = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Event handler aliases In addition to the `Window` interface, the event handler property `onoffline` is also available on the following targets: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("SVGSVGElement")}} ## Examples ```js // addEventListener version window.addEventListener("offline", (event) => { console.log("The network connection has been lost."); }); // onoffline version window.onoffline = (event) => { console.log("The network connection has been lost."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [`online`](/en-US/docs/Web/API/Window/online_event)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/requestfilesystem/index.md
--- title: "Window: requestFileSystem() method" short-title: requestFileSystem() slug: Web/API/Window/requestFileSystem page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.Window.requestFileSystem --- {{APIRef("HTML DOM")}}{{Deprecated_Header}}{{non-standard_header}} The non-standard {{domxref("Window")}} method **`requestFileSystem()`** method is a Google Chrome-specific method which lets a website or app gain access to a sandboxed file system for its own use. The returned {{domxref("FileSystem")}} is then available for use with the other [file system APIs](/en-US/docs/Web/API/File_and_Directory_Entries_API). > **Note:** This method is prefixed with `webkit` in all browsers that implement it. ## Syntax ```js-nolint requestFileSystem(type, size, successCallback) requestFileSystem(type, size, successCallback, errorCallback) ``` ### Parameters - `type` - : The type of storage to request. Specify `Window.TEMPORARY` if it's acceptable for the browser to delete the files at its own discretion, such as if storage space runs low, or `Window.PERSISTENT` if you need the files to remain in place unless the user or the website or app explicitly permit it. Persistent storage requires that the user grant the site quota. - `size` - : The amount of storage space you wish to have allocated for your app's use. - `successCallback` - : A function which is invoked when the file system has been successfully obtained. The callback receives a single parameter: a {{domxref("FileSystem")}} object representing the file system the app has permission to use. - `errorCallback` {{optional_inline}} - : An optional parameter specifying a function which is called if an error occurs while attempting to obtain the file system, or if the user denies permission to create or access the file system. The callback receives as input a single parameter: a `FileError` object describing the error. ### Return value None ({{jsxref("undefined")}}). ## Specifications As this method was removed from the [File and Directory Entries API](https://wicg.github.io/entries-api/) proposal, it has no official W3C or WHATWG specification. It is no longer on track to become a standard. ## Browser compatibility {{Compat}} ## See also - [File and Directory Entries API support in Firefox](/en-US/docs/Web/API/File_and_Directory_Entries_API/Firefox_support)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/orientationchange_event/index.md
--- title: "Window: orientationchange event" short-title: orientationchange slug: Web/API/Window/orientationchange_event page-type: web-api-event status: - deprecated browser-compat: api.Window.orientationchange_event --- {{APIRef}}{{Deprecated_Header}} The `orientationchange` event is fired when the orientation of the device has changed. This event is not cancelable and does not bubble. This event is deprecated. Listen for the {{domxref("ScreenOrientation.change_event", "change")}} event of the {{domxref("ScreenOrientation")}} interface instead. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("orientationchange", (event) => {}); onorientationchange = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Example You can use the `orientationchange` event in an {{domxref("EventTarget/addEventListener", "addEventListener")}} method: ```js window.addEventListener("orientationchange", (event) => { console.log( `the orientation of the device is now ${event.target.screen.orientation.angle}`, ); }); ``` Or use the `onorientationchange` event handler property: ```js window.onorientationchange = (event) => { console.log( `the orientation of the device is now ${event.target.screen.orientation.angle}`, ); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/unload_event/index.md
--- title: "Window: unload event" short-title: unload slug: Web/API/Window/unload_event page-type: web-api-event status: - deprecated browser-compat: api.Window.unload_event --- {{APIRef}}{{deprecated_header}} > **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: - {{domxref("Window/beforeunload_event", "beforeunload")}} (cancelable event) - {{domxref("Window/pagehide_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 ({{domxref("window.open")}}, {{domxref("window.alert", "alert")}}, {{domxref("window.confirm", "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 {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("unload", (event) => {}); onunload = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Event handler aliases In addition to the `Window` interface, the event handler property `onunload` is also available on the following targets: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("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](https://web.dev/articles/bfcache) (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`](/en-US/docs/Web/API/Document/visibilitychange_event) event. In browsers that don't support `visibilitychange` the next-best alternative is the [`pagehide`](/en-US/docs/Web/API/Window/pagehide_event) 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](https://developer.chrome.com/blog/page-lifecycle-api/#the-unload-event) 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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("Document/DOMContentLoaded_event", "DOMContentLoaded")}}, {{domxref("Document/readystatechange_event", "readystatechange")}}, {{domxref("Window/load_event", "load")}} - [Unloading Documents — unload a document](https://html.spec.whatwg.org/multipage/browsers.html#unloading-documents) - The [`visibilitychange`](/en-US/docs/Web/API/Document/visibilitychange_event) event. - [Don't lose user and app state, use Page Visibility](https://www.igvita.com/2015/11/20/dont-lose-user-and-app-state-use-page-visibility/) explains in detail why you should use `visibilitychange`, not `beforeunload`/`unload`. - [Page Lifecycle API](https://developer.chrome.com/blog/page-lifecycle-api/#developer-recommendations-for-each-state) gives best-practices guidance on handling page lifecycle behavior in your web applications. - [PageLifecycle.js](https://github.com/GoogleChromeLabs/page-lifecycle): a JavaScript library that deals with cross-browser inconsistencies in page lifecycle behavior. - [Back/forward cache](https://web.dev/articles/bfcache) explains what the back/forward cache is, and its implications for various page lifecycle events.
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/frameelement/index.md
--- title: "Window: frameElement property" short-title: frameElement slug: Web/API/Window/frameElement page-type: web-api-instance-property browser-compat: api.Window.frameElement --- {{ApiRef}} The **`Window.frameElement`** property returns the element (such as {{HTMLElement("iframe")}} or {{HTMLElement("object")}}) in which the window is embedded. > **Note:** Despite this property's name, it works for documents embedded > within any embedding point, including {{HTMLElement("object")}}, > {{HTMLElement("iframe")}}, or {{HTMLElement("embed")}}. ## Value The element which the window is embedded into. If the window isn't embedded into another document, or if the document into which it's embedded has a different {{glossary("origin")}}, the value is [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null) instead. ## Examples ```js const frameEl = window.frameElement; // If we're embedded, change the containing element's URL to 'https://mozilla.org/' if (frameEl) { frameEl.src = "https://mozilla.org/"; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.frames")}} returns an array-like object, listing the direct sub-frames of the current window. - {{domxref("window.parent")}} returns the parent window, which is the window containing the `frameElement` of the child window.
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/scrollbars/index.md
--- title: "Window: scrollbars property" short-title: scrollbars slug: Web/API/Window/scrollbars page-type: web-api-instance-property browser-compat: api.Window.scrollbars --- {{APIRef()}} Returns the `scrollbars` object. This is one of a group of `Window` properties that contain a boolean `visible` property, that used to represent whether or not a particular part of a web browser's user interface was visible. For privacy and interoperability reasons, the value of the `visible` property is now `false` if this `Window` is a popup, and `true` otherwise. ## Value An object containing a single property: - `visible` {{ReadOnlyInline}} - : A boolean property, `false` if this `Window` is a popup, and `true` otherwise. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.locationbar")}} - {{domxref("window.menubar")}} - {{domxref("window.personalbar")}} - {{domxref("window.statusbar")}} - {{domxref("window.toolbar")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/vrdisplayactivate_event/index.md
--- title: "Window: vrdisplayactivate event" short-title: vrdisplayactivate slug: Web/API/Window/vrdisplayactivate_event page-type: web-api-event status: - deprecated - non-standard browser-compat: api.Window.vrdisplayactivate_event --- {{APIRef("Window")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`vrdisplayactivate`** event of the [WebVR API](/en-US/docs/Web/API/WebVR_API) is fired when a VR display is able to be presented to, for example if an HMD has been moved to bring it out of standby, or woken up by being put on. > **Note:** This event was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("vrdisplayactivate", (event) => {}); onvrdisplayactivate = (event) => {}; ``` ## Event type A {{domxref("VRDisplayEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("VRDisplayEvent")}} ## Event properties _`VRDisplayEvent` also inherits properties from its parent object, {{domxref("Event")}}._ - {{domxref("VRDisplayEvent.display")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : The {{domxref("VRDisplay")}} associated with this event. - {{domxref("VRDisplayEvent.reason")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : A human-readable reason why the event was fired. ## Examples You can use the `vrdisplayactivate` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js window.addEventListener("vrdisplayactivate", () => { info.textContent = "Display activated."; reportDisplays(); }); ``` Or use the `onvrdisplayactivate` event handler property: ```js window.onvrdisplayactivate = () => { info.textContent = "Display activated."; reportDisplays(); }; ``` ## Specifications This event was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard. Until all browsers have implemented the new [WebXR Device API](https://immersive-web.github.io/webxr/), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/). ## Browser compatibility {{Compat}} ## See also - [WebVR API](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/outerwidth/index.md
--- title: "Window: outerWidth property" short-title: outerWidth slug: Web/API/Window/outerWidth page-type: web-api-instance-property browser-compat: api.Window.outerWidth --- {{APIRef}} **`Window.outerWidth`** read-only property returns the width of the outside of the browser window. It represents the width of the whole browser window including sidebar (if expanded), window chrome and window resizing borders/handles. ## Notes To change the size of a window, see {{domxref("window.resizeBy()")}} and {{domxref("window.resizeTo()")}}. To get the inner width of a window, i.e. the width of the page being displayed, see {{domxref("window.innerWidth")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.outerHeight")}}, {{domxref("window.innerHeight")}}, {{domxref("window.innerWidth")}} - {{domxref("window.resizeBy()")}}, {{domxref("window.resizeTo()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/screen/index.md
--- title: "Window: screen property" short-title: screen slug: Web/API/Window/screen page-type: web-api-instance-property browser-compat: api.Window.screen --- {{APIRef("CSSOM")}} The {{DOMxRef("Window")}} property **`screen`** returns a reference to the screen object associated with the window. The `screen` object, implementing the {{DOMxRef("Screen")}} interface, is a special object for inspecting properties of the screen on which the current window is being rendered. ## Value A {{DOMxRef("Screen")}} object. ## Examples ```js if (screen.pixelDepth < 8) { // use low-color version of page } else { // use regular, colorful page } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/sessionstorage/index.md
--- title: "Window: sessionStorage property" short-title: sessionStorage slug: Web/API/Window/sessionStorage page-type: web-api-instance-property browser-compat: api.Window.sessionStorage --- {{APIRef("Web Storage API")}} The read-only **`sessionStorage`** property accesses a session {{DOMxRef("Storage")}} object for the current {{glossary("origin")}}. `sessionStorage` is similar to {{DOMxRef("Window.localStorage", "localStorage")}}; the difference is that while data in `localStorage` doesn't expire, data in `sessionStorage` is cleared when the _page session_ ends. - Whenever a document is loaded in a particular tab in the browser, a unique page session gets created and assigned to that particular tab. That page session is valid only for that particular tab. - A page session lasts as long as the tab or the browser is open, and survives over page reloads and restores. - **Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.** - Opening multiple tabs/windows with the same URL creates `sessionStorage` for each tab/window. - Duplicating a tab copies the tab's `sessionStorage` into the new tab. - Closing a tab/window ends the session and clears objects in `sessionStorage`. Data stored in `sessionStorage` **is specific to the protocol of the page**. In particular, data stored by a script on a site accessed with HTTP (e.g., [http://example.com](https://example.com)) is put in a different `sessionStorage` object from the same site accessed with HTTPS (e.g., <https://example.com>). The keys and the values are _always_ in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings. ## Value A {{DOMxRef("Storage")}} object which can be used to access the current origin's session storage space. ### Exceptions - `SecurityError` - : Thrown in one of the following cases: - The origin is not [a valid scheme/host/port tuple](/en-US/docs/Web/Security/Same-origin_policy#definition_of_an_origin). This can happen if the origin uses the `file:` or `data:` schemes, for example. - The request violates a policy decision. For example, the user has configured the browsers to prevent the page from persisting data. Note that if the user blocks cookies, browsers will probably interpret this as an instruction to prevent the page from persisting data. ## Examples ### Basic usage ```js // Save data to sessionStorage sessionStorage.setItem("key", "value"); // Get saved data from sessionStorage let data = sessionStorage.getItem("key"); // Remove saved data from sessionStorage sessionStorage.removeItem("key"); // Remove all saved data from sessionStorage sessionStorage.clear(); ``` ### Saving text between refreshes The following example autosaves the contents of a text field, and if the browser is refreshed, restores the text field content so that no writing is lost. ```js // Get the text field that we're going to track let field = document.getElementById("field"); // See if we have an autosave value // (this will only happen if the page is accidentally refreshed) if (sessionStorage.getItem("autosave")) { // Restore the contents of the text field field.value = sessionStorage.getItem("autosave"); } // Listen for changes in the text field field.addEventListener("change", () => { // And save the results into the session storage object sessionStorage.setItem("autosave", field.value); }); ``` > **Note:** Please refer to the [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API) article for a full example. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Using the Web Storage API](/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API) - {{DOMxRef("Window.localStorage")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/status/index.md
--- title: "Window: status property" short-title: status slug: Web/API/Window/status page-type: web-api-instance-property status: - deprecated browser-compat: api.Window.status --- {{APIRef}}{{Deprecated_Header}} The **`status`** property of the {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/getselection/index.md
--- title: "Window: getSelection() method" short-title: getSelection() slug: Web/API/Window/getSelection page-type: web-api-instance-method browser-compat: api.Window.getSelection --- {{ ApiRef() }} The **`Window.getSelection()`** method returns a {{domxref("Selection")}} object representing the range of text selected by the user or the current position of the caret. ## Syntax ```js-nolint getSelection() ``` ### Parameters None. ### Return value A {{domxref("Selection")}} object. When cast to string, either by appending an empty string (`""`) or using {{domxref("Selection.toString()")}}, this object returns the text selected. When called on an {{htmlelement("iframe")}} that is not displayed (e.g., where `display: none` is set) Firefox will return `null`, whereas other browsers will return a {{domxref("Selection")}} object with {{domxref("Selection.type")}} set to `None`. ## Examples ```js function foo() { const selObj = window.getSelection(); alert(selObj); const selRange = selObj.getRangeAt(0); // do stuff with the range } ``` ## Notes ### String representation of the Selection object In JavaScript, when an object is passed to a function expecting a string (like {{ Domxref("window.alert()") }} or {{ Domxref("document.write()") }}), the object's {{jsxref("Object.toString", "toString()")}} method is called and the returned value is passed to the function. This can make the object appear to be a string when used with other functions when it is really an object with properties and methods. In the above example, `selObj.toString()` is automatically called when it is passed to {{domxref("window.alert()")}}. However, attempting to use a JavaScript [String](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) property or method such as [`length`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length) or [`substr`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr) directly on a {{domxref("Selection")}} object will result in an error if it does not have that property or method and may return unexpected results if it does. To use a `Selection` object as a string, call its `toString()` method directly: ```js const selectedText = selObj.toString(); ``` - `selObj` is a `Selection` object. - `selectedText` is a string (Selected text). ### Related objects You can call {{domxref("Document.getSelection()")}}, which works identically to `Window.getSelection()`. It is worth noting that currently `getSelection()` doesn't work on the content of {{htmlelement("textarea")}} and {{htmlelement("input")}} elements in Firefox and Edge (Legacy). {{domxref("HTMLInputElement.setSelectionRange()")}} or the `selectionStart` and `selectionEnd` properties could be used to work around this. Notice also the difference between _selection_ and _focus_. {{domxref("Document.activeElement")}} returns the focused element. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Selection API](/en-US/docs/Web/API/Selection) - {{domxref("Selection")}} - {{domxref("Range")}} - {{domxref("Document.getSelection()")}} - {{domxref("HTMLInputElement.setSelectionRange()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/orientation/index.md
--- title: "Window: orientation property" short-title: orientation slug: Web/API/Window/orientation page-type: web-api-instance-property status: - deprecated browser-compat: api.Window.orientation --- {{APIRef}}{{Deprecated_Header}} Returns the orientation in degrees (in 90-degree increments) of the viewport relative to the device's natural orientation. Its only possible values are `-90`, `0`, `90`, and `180`. Positive values are counterclockwise; negative values are clockwise. This property is deprecated. Use the {{domxref("Screen.orientation")}} property instead, available on the {{domxref("window.screen")}} property. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/showmodaldialog/index.md
--- title: "Window: showModalDialog() method" short-title: showModalDialog() slug: Web/API/Window/showModalDialog page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.Window.showModalDialog --- {{APIRef}}{{Deprecated_Header}}{{Non-standard_Header}} > **Warning:** This feature has been removed. Please fix your websites and applications. > > This method was removed in Chrome 43 and Firefox 56. The **`Window.showModalDialog()`** created and displayed a modal dialog box containing a specified HTML document. ## Syntax ```js-nolint showModalDialog(uri) showModalDialog(uri, arguments) showModalDialog(uri, arguments, options) ``` ### Parameters - `uri` - : Is the URL of the document to display in the dialog. - `arguments` {{optional_inline}} - : Values passed to the dialog. property. - `options` {{optional_inline}} - : A string specifying window ornamentation for the dialog, using one or more semicolon delimited values: <table class="no-markdown"> <tbody> <tr> <th>Syntax</th> <th>Description</th> </tr> <tr> <td><code>center: {on | off | yes | no | 1 | 0 }</code></td> <td> If <code>on</code>, <code>yes</code>, or <code>1</code>, the dialog window is centered on the desktop; otherwise it's hidden. Default is <code>yes</code>. </td> </tr> <tr> <td> <code>dialogheight: <em>height</em></code> </td> <td>The height of the dialog box in pixels.</td> </tr> <tr> <td> <code>dialogleft: <em>left</em></code> </td> <td>Distance of the dialog box from the left edge of the desktop.</td> </tr> <tr> <td> <code>dialogwidth: <em>width</em></code> </td> <td>The width of the dialog box in pixels.</td> </tr> <tr> <td> <code>dialogtop: <em>top</em></code> </td> <td>Distance of the dialog box from the top edge of the desktop.</td> </tr> <tr> <td><code>resizable: {on | off | yes | no | 1 | 0 }</code></td> <td> If this argument's value is <code>on</code>, <code>yes</code>, or 1, the dialog window can be resized by the user; otherwise its size is fixed. The default value is <code>no</code>. </td> </tr> <tr> <td><code>scroll: {on | off | yes | no | 1 | 0 }</code></td> <td> If <code>on</code>, <code>yes</code>, or 1, the dialog window has scroll bars; otherwise its size is fixed. Default is <code>no</code>. </td> </tr> </tbody> </table> > **Note:** Firefox does not implement the `dialogHide`, `edge`, `status`, or `unadorned` arguments. ### Return value Holds the `returnValue` property as set by the document specified by `uri`. ## Specifications - [MSDN page for `showModalDialog`](<https://msdn.microsoft.com/library/ms536759(VS.85).aspx>) ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("dialog")}}, a replacement for `window.showModalDialog()`. - [showModalDialog Polyfill](https://github.com/niutech/showModalDialog) using a {{HTMLElement("dialog")}} and [generators](/en-US/docs/Web/JavaScript/Reference/Statements/function*)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/sidebar/index.md
--- title: "Window: sidebar property" short-title: sidebar slug: Web/API/Window/sidebar page-type: web-api-instance-property status: - deprecated - non-standard --- {{APIRef}} {{Deprecated_Header}} > **Warning:** This non-standard Firefox-only alias of the [`window.external`](/en-US/docs/Web/API/Window/external) property [has been removed](#browser_compatibility). 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: <table class="fullwidth-table"> <tbody> <tr> <th>Method</th> <th>Description (SeaMonkey)</th> <th>Description (Firefox)</th> </tr> <tr> <td> <code>addPanel(<var>title</var>, <var>contentURL</var>, "")</code> </td> <td>Adds a sidebar panel.</td> <td rowspan="2"> Obsolete since Firefox 23 (only present in SeaMonkey).<br />End users can use the "load this bookmark in the sidebar" option instead. Also see <a href="/en-US/docs/Mozilla/Creating_a_Firefox_sidebar" >Creating a Firefox sidebar.</a > </td> </tr> <tr> <td> <code >addPersistentPanel(<var>title</var>, <var>contentURL</var>, "")</code > </td> <td>Adds a sidebar panel, which is able to work in the background.</td> </tr> <tr> <td> <code>AddSearchProvider(<em>descriptionURL)</em></code> </td> <td colspan="2"> Dummy function; does nothing. See <a href="/en-US/docs/Web/OpenSearch#Autodiscovery_of_search_plugins" >Autodiscovery of search plugins</a >. </td> </tr> <tr> <td> <code >addSearchEngine(<var>engineURL</var>, <var>iconURL</var>, <var>suggestedTitle</var>, <var>suggestedCategory</var>)</code > {{deprecated_inline}} </td> <td colspan="2"> <p> Installs a search engine (Sherlock). <a href="/en-US/docs/Web/API/Window/sidebar/Adding_search_engines_from_Web_pages#Installing_Sherlock_plugins" title="Adding_search_engines_from_web_pages" >Adding Sherlock search engines </a >contains more details. </p> <div class="note"> <p> <strong>Note:</strong> This was made obsolete in Firefox 44, and has been removed completely in Firefox 59. </p> </div> </td> </tr> <tr> <td> <code>IsSearchProviderInstalled(<em>descriptionURL)</em></code> </td> <td colspan="2"> Indicates if a specific search provider (OpenSearch) is installed. </td> </tr> </tbody> </table> ## Specifications Mozilla-specific. Not part of any standard. ## Browser compatibility Removed in Firefox 102. For more information see Firefox compatibility information in [`window.external`](/en-US/docs/Web/API/Window/external#browser_compatibility).
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/pageshow_event/index.md
--- title: "Window: pageshow event" short-title: pageshow slug: Web/API/Window/pageshow_event page-type: web-api-event browser-compat: api.Window.pageshow_event --- {{APIRef("HTML DOM")}} The **`pageshow`** event is sent to a {{domxref("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 {{domxref("Window/load_event", "load")}} event. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("pageshow", (event) => {}); onpageshow = (event) => {}; ``` ## Event type A {{domxref("PageTransitionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PageTransitionEvent")}} ## Event properties - {{domxref("PageTransitionEvent.persisted")}} {{ReadOnlyInline}} - : 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: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("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 {{domxref("PageTransitionEvent.persisted", "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 {{EmbedLiveSample("Examples", 640, 250)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window.pagehide_event", "pagehide")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/setimmediate/index.md
--- title: "Window: setImmediate() method" short-title: setImmediate() slug: Web/API/Window/setImmediate page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.Window.setImmediate --- {{APIRef("HTML DOM")}} {{deprecated_header}}{{non-standard_header}} This method is used to break up long running operations and run a callback function immediately after the browser has completed other operations such as events and display updates. ## Syntax ```js-nolint setImmediate(func) setImmediate(func, param1) setImmediate(func, param1, param2) setImmediate(func, param1, param2, /* …, */ paramN) ``` ### Parameters - `func` - : The function you wish to call. - `param1`, …, `paramN` - : All parameters will be passed directly to your function. ### Return value The ID of the immediate which can be used later with {{DOMxRef("window.clearImmediate")}}. ## Notes The {{DOMxRef("Window.clearImmediate", "clearImmediate")}} method can be used to clear the immediate actions, just like {{DOMxRef("clearTimeout")}} for {{DOMxRef("setTimeout()")}}. This method can be used instead of the `setTimeout(fn, 0)` method to execute [heavy operations](https://humanwhocodes.com/blog/2009/08/11/timed-array-processing-in-javascript/). The feature can be emulated in a few different ways: - {{DOMxRef("Window.postMessage", "postMessage")}} can be used to trigger an immediate but yielding callback. - {{DOMxRef("MessageChannel")}} can be used reliably inside of Web Workers whereas the semantics of postMessage mean it cannot be used there. - `setTimeout(fn, 0)` _can_ potentially be used, however as it is clamped to 4ms for timers nested more than 5 levels deep [per the HTML spec](https://html.spec.whatwg.org/multipage/webappapis.html#timers), it does not make for a suitable polyfill for the natural immediacy of `setImmediate`. All of these techniques are incorporated into a [robust setImmediate polyfill](https://github.com/YuzuJS/setImmediate). ## Specifications Not part of any current specifications. The [Efficient Script Yielding](https://w3c.github.io/setImmediate/#si-setImmediate) specification is no longer being worked on. ## Browser compatibility {{Compat}} ## See also - [Polyfill of `setImmediate` in `core-js`](https://github.com/zloirock/core-js#setimmediate) - [Microsoft `setImmediate` API Demo](https://jphpsf.github.io/setImmediate-shim-demo/) - {{DOMxRef("Window.clearImmediate()")}} - {{DOMxRef("Window.requestIdleCallback()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/afterprint_event/index.md
--- title: "Window: afterprint event" short-title: afterprint slug: Web/API/Window/afterprint_event page-type: web-api-event browser-compat: api.Window.afterprint_event --- {{APIRef}} The **`afterprint`** event is fired after the associated document has started printing or the print preview has been closed. The {{domxref("Window.beforeprint_event", "beforeprint")}} and `afterprint` events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed. In general, you should prefer the use of a [`@media print`](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries#targeting_media_types) CSS at-rule, but it may be necessary to use these events in some cases. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("afterprint", (event) => {}); onafterprint = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples Using `addEventListener()`: ```js window.addEventListener("afterprint", (event) => { console.log("After print"); }); ``` Using the `onafterprint` event handler property: ```js window.onafterprint = (event) => { console.log("After print"); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("Window/beforeprint_event", "beforeprint")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/scrollbypages/index.md
--- title: "Window: scrollByPages() method" short-title: scrollByPages() slug: Web/API/Window/scrollByPages page-type: web-api-instance-method status: - non-standard browser-compat: api.Window.scrollByPages --- {{ ApiRef() }} {{Non-standard_header}} The **`Window.scrollByPages()`** method scrolls the current document by the specified number of pages. ## Syntax ```js-nolint scrollByPages(pages) ``` ### Parameters - `pages` is the number of pages to scroll. It may be a positive or negative integer. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js // scroll down the document by 1 page window.scrollByPages(1); // scroll up the document by 1 page window.scrollByPages(-1); ``` ## Specifications DOM Level 0. Not part of specification. ## Browser compatibility {{Compat}} ## See also - {{domxref("window.scroll()")}} - {{domxref("window.scrollBy()")}} - {{domxref("window.scrollByLines()")}} - {{domxref("window.scrollTo()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/deviceorientationabsolute_event/index.md
--- title: "Window: deviceorientationabsolute event" short-title: deviceorientationabsolute slug: Web/API/Window/deviceorientationabsolute_event page-type: web-api-event browser-compat: api.Window.deviceorientationabsolute_event --- {{APIRef("Device Orientation Events")}}{{securecontext_header}} The **`deviceorientationabsolute`** event is fired when absolute device orientation changes. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("deviceorientationabsolute", (event) => {}); ondeviceorientationabsolute = (event) => {}; ``` ## Event type A {{domxref("DeviceOrientationEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("DeviceOrientationEvent")}} ## Event properties - {{domxref("DeviceOrientationEvent.absolute")}} {{ReadOnlyInline}} - : A boolean that indicates whether the device is providing orientation data absolutely. - {{domxref("DeviceOrientationEvent.alpha")}} {{ReadOnlyInline}} - : A number representing the motion of the device around the z axis, expressed in degrees with values ranging from 0 (inclusive) to 360 (exclusive). - {{domxref("DeviceOrientationEvent.beta")}} {{ReadOnlyInline}} - : A number representing the motion of the device around the x axis, expressed in degrees with values ranging from -180 (inclusive) to 180 (exclusive). This represents a front to back motion of the device. - {{domxref("DeviceOrientationEvent.gamma")}} {{ReadOnlyInline}} - : A number representing the motion of the device around the y axis, expressed in degrees with values ranging from -90 (inclusive) to 90 (exclusive). This represents a left to right motion of the device. - `DeviceOrientationEvent.webkitCompassHeading` {{Non-standard_Inline}} {{ReadOnlyInline}} - : A number represents the difference between the motion of the device around the z axis of the world system and the direction of north, expressed in degrees with values ranging from 0 to 360. - `DeviceOrientationEvent.webkitCompassAccuracy` {{Non-standard_Inline}} {{ReadOnlyInline}} - : The accuracy of the compass given as a positive or negative deviation. It's usually 10. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{DOMxRef("window.devicemotion_event", "devicemotion")}} event - {{DOMxRef("window.deviceorientation_event", "deviceorientation")}} event - [Detecting device orientation](/en-US/docs/Web/API/Device_orientation_events/Detecting_device_orientation)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/print/index.md
--- title: "Window: print() method" short-title: print() slug: Web/API/Window/print page-type: web-api-instance-method browser-compat: api.Window.print --- {{ ApiRef() }} 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-nolint print() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Printing](/en-US/docs/Web/CSS/CSS_media_queries/Printing) - {{ domxref("window.beforeprint_event", "beforeprint") }} event - {{ domxref("window.afterprint_event", "afterprint") }} event
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/visualviewport/index.md
--- title: "Window: visualViewport property" short-title: visualViewport slug: Web/API/Window/visualViewport page-type: web-api-instance-property browser-compat: api.Window.visualViewport --- {{APIRef("Visual Viewport")}} The **`visualViewport`** read-only property of the {{domxref("Window")}} interface returns a {{domxref("VisualViewport")}} object representing the visual viewport for a given window, or `null` if current document is not fully active. ## Value A {{domxref("VisualViewport")}} object. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/devicemotion_event/index.md
--- title: "Window: devicemotion event" short-title: devicemotion slug: Web/API/Window/devicemotion_event page-type: web-api-event browser-compat: api.Window.devicemotion_event --- {{APIRef("Device Orientation Events")}}{{securecontext_header}} The **`devicemotion`** event is fired at a regular interval and indicates the acceleration rate of the device with/without the contribution of the gravity force at that time. It also provides information about the rate of rotation, if available. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("devicemotion", (event) => {}); ondevicemotion = (event) => {}; ``` ## Event type A {{domxref("DeviceMotionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("DeviceMotionEvent")}} ## Event properties - {{DOMxRef("DeviceMotionEvent.acceleration")}} {{ReadOnlyInline}} - : An object giving the acceleration of the device on the three axis: x, y, and z. Acceleration is expressed in [m/s²](https://en.wikipedia.org/wiki/Meter_per_second_squared). - {{DOMxRef("DeviceMotionEvent.accelerationIncludingGravity")}} {{ReadOnlyInline}} - : An object giving the acceleration of the device on the three axis: x, y, and z with the effect of gravity. Acceleration is expressed in [m/s²](https://en.wikipedia.org/wiki/Meter_per_second_squared). - {{DOMxRef("DeviceMotionEvent.rotationRate")}} {{ReadOnlyInline}} - : An object giving the rate of change of the device's orientation on the three orientation axis: alpha, beta and gamma. Rotation rate is expressed in degrees per seconds. - {{DOMxRef("DeviceMotionEvent.interval")}} {{ReadOnlyInline}} - : A number representing the interval of time, in milliseconds, at which data is obtained from the device. ## Examples ```js function handleMotionEvent(event) { const x = event.accelerationIncludingGravity.x; const y = event.accelerationIncludingGravity.y; const z = event.accelerationIncludingGravity.z; // Do something awesome. } window.addEventListener("devicemotion", handleMotionEvent, true); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window.deviceorientation_event", "deviceorientation")}} - [DeviceOrientation Event](https://www.w3.org/TR/orientation-event/#devicemotion)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/cookiestore/index.md
--- title: "Window: cookieStore property" short-title: cookieStore slug: Web/API/Window/cookieStore page-type: web-api-instance-property status: - experimental browser-compat: api.Window.cookieStore --- {{securecontext_header}}{{APIRef("Cookie Store API")}}{{SeeCompatTable}} The **`cookieStore`** read-only property of the {{domxref("Window")}} interface returns a reference to the {{domxref("CookieStore")}} object for the current document context. This is an entry point for the [Cookie Store API](/en-US/docs/Web/API/Cookie_Store_API). ## Value A {{domxref("CookieStore")}} object instance. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/matchmedia/index.md
--- title: "Window: matchMedia() method" short-title: matchMedia() slug: Web/API/Window/matchMedia page-type: web-api-instance-method browser-compat: api.Window.matchMedia --- {{APIRef}} The {{domxref("Window")}} interface's **`matchMedia()`** method returns a new {{domxref("MediaQueryList")}} object that can then be used to determine if the {{domxref("document")}} matches the [media query](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) string, as well as to monitor the document to detect when it matches (or stops matching) that media query. ## Syntax ```js-nolint matchMedia(mediaQueryString) ``` ### Parameters - `mediaQueryString` - : A string specifying the media query to parse into a {{domxref("MediaQueryList")}}. ### Return value A new {{domxref("MediaQueryList")}} object for the media query. Use this object's properties and events to detect matches and to monitor for changes to those matches over time. ## Usage notes You can use the returned media query to perform both instantaneous and event-driven checks to see if the document matches the media query. To perform a one-time, instantaneous check to see if the document matches the media query, look at the value of the {{domxref("MediaQueryList.matches", "matches")}} property, which will be `true` if the document meets the media query's requirements. If you need to be kept aware of whether or not the document matches the media query at all times, you can instead watch for the {{domxref("MediaQueryList.change_event", "change")}} event to be delivered to the object. There's [a good example of this](/en-US/docs/Web/API/Window/devicePixelRatio#monitoring_screen_resolution_or_zoom_level_changes) in the article on {{domxref("Window.devicePixelRatio")}}. ## Examples This example runs the media query `(max-width: 600px)` and displays the value of the resulting `MediaQueryList`'s `matches` property in a {{HTMLElement("span")}}; as a result, the output will say "true" if the viewport is less than or equal to 600 pixels wide, and will say "false" if the window is wider than that. ### JavaScript ```js let mql = window.matchMedia("(max-width: 600px)"); document.querySelector(".mq-value").innerText = mql.matches; ``` The JavaScript code passes the media query to match into {{domxref("Window.matchMedia", "matchMedia()")}} to compile it, then sets the `<span>`'s {{domxref("HTMLElement.innerText", "innerText")}} to the value of the results' {{domxref("MediaQueryList.matches", "matches")}} property, so that it indicates whether or not the document matches the media query at the moment the page was loaded. ### HTML ```html <span class="mq-value"></span> ``` A simple `<span>` to receive the output. ```css hidden .mq-value { font: 18px arial, sans-serif; font-weight: bold; color: #88f; padding: 0.4em; border: 1px solid #dde; } ``` ### Result {{EmbedLiveSample("Examples", "100%", "60")}} See [Testing media queries programmatically](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries) for additional code examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) - [Using media queries from code](/en-US/docs/Web/CSS/CSS_media_queries/Testing_media_queries) - {{domxref("MediaQueryList")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/scrollby/index.md
--- title: "Window: scrollBy() method" short-title: scrollBy() slug: Web/API/Window/scrollBy page-type: web-api-instance-method browser-compat: api.Window.scrollBy --- {{ APIRef() }} The **`Window.scrollBy()`** method scrolls the document in the window by the given amount. ## Syntax ```js-nolint scrollBy(x-coord, y-coord) scrollBy(options) ``` ### Parameters - `x-coord` is the horizontal pixel value that you want to scroll by. - `y-coord` is the vertical pixel value that you want to scroll by. \- or - - `options` - : A dictionary containing the following parameters: - `top` - : Specifies the number of pixels along the Y axis to scroll the window or element. - `left` - : Specifies the number of pixels along the X axis to scroll the window or element. - `behavior` - : Specifies whether the scrolling should animate smoothly (`smooth`), happen instantly in a single jump (`instant`), or let the browser choose (`auto`, default). ### Return value None ({{jsxref("undefined")}}). ## Examples To scroll down one page: ```js window.scrollBy(0, window.innerHeight); ``` To scroll up: ```js window.scrollBy(0, -window.innerHeight); ``` Using `options`: ```js window.scrollBy({ top: 100, left: 100, behavior: "smooth", }); ``` ## Notes `window.scrollBy()` scrolls by a particular amount, whereas {{domxref("window.scroll()")}} scrolls to an absolute position in the document. See also {{domxref("window.scrollByLines()")}} and {{domxref("window.scrollByPages()")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/top/index.md
--- title: "Window: top property" short-title: top slug: Web/API/Window/top page-type: web-api-instance-property browser-compat: api.Window.top --- {{APIRef}} Returns a reference to the topmost window in the window hierarchy. ## Value The reference to the topmost window. ## Notes Where the {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/screentop/index.md
--- title: "Window: screenTop property" short-title: screenTop slug: Web/API/Window/screenTop page-type: web-api-instance-property browser-compat: api.Window.screenTop --- {{APIRef}} The **`Window.screenTop`** read-only property returns the vertical distance, in CSS pixels, from the top border of the user's browser viewport to the top side of the screen. > **Note:** `screenTop` is an alias of the older > {{domxref("Window.screenY")}} property. `screenTop` 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 top edge of the browser viewport to the top edge of the screen. ## Examples In our [screenleft-screentop](https://mdn.github.io/dom-examples/screenleft-screentop/) example, you'll see a canvas onto which has been drawn a circle. In this example we are using `screenLeft`/`screenTop` plus {{domxref("Window.requestAnimationFrame()")}} to constantly redraw the circle in the same physical position on the screen, even if the window position is moved. ```js initialLeft = window.screenLeft + canvasElem.offsetLeft; initialTop = window.screenTop + canvasElem.offsetTop; function positionElem() { let newLeft = window.screenLeft + canvasElem.offsetLeft; let newTop = window.screenTop + canvasElem.offsetTop; let leftUpdate = initialLeft - newLeft; let topUpdate = initialTop - newTop; ctx.fillStyle = "rgb(0 0 0)"; ctx.fillRect(0, 0, width, height); ctx.fillStyle = "rgb(0 0 255)"; ctx.beginPath(); ctx.arc( leftUpdate + width / 2, topUpdate + height / 2 + 35, 50, degToRad(0), degToRad(360), false, ); ctx.fill(); pElem.textContent = `Window.screenLeft: ${window.screenLeft}, Window.screenTop: ${window.screenTop}`; window.requestAnimationFrame(positionElem); } window.requestAnimationFrame(positionElem); ``` Also in the code we include a snippet that detects whether `screenLeft` is supported, and if not, polyfills in `screenLeft`/`screenTop` using {{domxref("Window.screenX")}}/{{domxref("Window.screenY")}}. ```js if (!window.screenLeft) { window.screenLeft = window.screenX; window.screenTop = window.screenY; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.screenLeft")}} - {{domxref("Window.screenY")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/vrdisplayconnect_event/index.md
--- title: "Window: vrdisplayconnect event" short-title: vrdisplayconnect slug: Web/API/Window/vrdisplayconnect_event page-type: web-api-event status: - deprecated - non-standard browser-compat: api.Window.vrdisplayconnect_event --- {{APIRef("Window")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`vrdisplayconnect`** event of the [WebVR API](/en-US/docs/Web/API/WebVR_API) is fired when a compatible VR display is connected to the computer. > **Note:** This event was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("vrdisplayconnect", (event) => {}); onvrdisplayconnect = (event) => {}; ``` ## Event type A {{domxref("VRDisplayEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("VRDisplayEvent")}} ## Event properties _`VRDisplayEvent` also inherits properties from its parent object, {{domxref("Event")}}._ - {{domxref("VRDisplayEvent.display")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : The {{domxref("VRDisplay")}} associated with this event. - {{domxref("VRDisplayEvent.reason")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : A human-readable reason why the event was fired. ## Examples You can use the `vrdisplayconnect` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js window.addEventListener("vrdisplayconnect", () => { info.textContent = "Display connected."; reportDisplays(); }); ``` Or use the `onvrdisplayconnect` event handler property: ```js window.onvrdisplayconnect = () => { info.textContent = "Display connected."; reportDisplays(); }; ``` ## Specifications This event was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard. Until all browsers have implemented the new [WebXR Device API](https://immersive-web.github.io/webxr/), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/). ## Browser compatibility {{Compat}} ## See also - [WebVR API](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/scrollmaxx/index.md
--- title: "Window: scrollMaxX property" short-title: scrollMaxX slug: Web/API/Window/scrollMaxX page-type: web-api-instance-property status: - non-standard browser-compat: api.Window.scrollMaxX --- {{APIRef}} {{Non-standard_header}} 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](/en-US/docs/Web/API/Window/innerWidth) + window\.scrollMaxX, because {{domxref("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 {{domxref("element.scrollWidth","document.body.scrollWidth")}}. See also {{domxref("window.scrollMaxY")}}. ## Specifications This is not part of any specification. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/cut_event/index.md
--- title: "Window: cut event" short-title: cut slug: Web/API/Window/cut_event page-type: web-api-event browser-compat: api.Element.cut_event --- {{APIRef}} The **`cut`** event is fired when the user has initiated a "cut" action through the browser's user interface. The original target for this event is the {{domxref("Element")}} that was the intended target of the cut action. You can listen for this event on the {{domxref("Window")}} interface to handle it in the capture or bubbling phases. For full details on this event please see the page on the [Element: cut event](/en-US/docs/Web/API/Element/cut_event). ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("cut", (event) => {}); oncut = (event) => {}; ``` ## Event type A {{domxref("ClipboardEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("ClipboardEvent")}} ## Examples ```js window.addEventListener("cut", (event) => { console.log("cut action initiated"); }); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: {{domxref("Window/copy_event", "copy")}}, {{domxref("Window/paste_event", "paste")}} - This event on {{domxref("Element")}} targets: {{domxref("Element/cut_event", "cut")}} - This event on {{domxref("Document")}} targets: {{domxref("Document/cut_event", "cut")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/mozinnerscreenx/index.md
--- title: "Window: mozInnerScreenX property" short-title: mozInnerScreenX slug: Web/API/Window/mozInnerScreenX page-type: web-api-instance-property status: - non-standard browser-compat: api.Window.mozInnerScreenX --- {{APIRef}}{{Non-standard_Header}} 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 {{Compat}} ## See also - {{domxref("window.mozInnerScreenY")}} - `nsIDOMWindowUtils.screenPixelsPerCSSPixel`
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/gamepaddisconnected_event/index.md
--- title: "Window: gamepaddisconnected event" short-title: gamepaddisconnected slug: Web/API/Window/gamepaddisconnected_event page-type: web-api-event browser-compat: api.Window.gamepaddisconnected_event --- {{APIRef}} The `gamepaddisconnected` event is fired when the browser detects that a gamepad has been disconnected. The event will not fire if disallowed by the document's {{httpheader('Permissions-Policy/gamepad','gamepad')}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). This event is not cancelable and does not bubble. ## Examples To be informed when a gamepad is disconnected, you can add a handler to the window using {{domxref("EventTarget.addEventListener", "addEventListener()")}}, like this: ```js window.addEventListener("gamepaddisconnected", (event) => { console.log("Lost connection with the gamepad."); }); ``` Alternatively, you can use the `window.ongamepaddisconnected` event handler property to establish a handler for the `gamepaddisconnected` event: ```js window.ongamepaddisconnected = (event) => { console.log("Lost connection with the gamepad."); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [gamepadconnected](/en-US/docs/Web/API/Window/gamepadconnected_event) - [Using Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/scrollbylines/index.md
--- title: "Window: scrollByLines() method" short-title: scrollByLines() slug: Web/API/Window/scrollByLines page-type: web-api-instance-method status: - non-standard browser-compat: api.Window.scrollByLines --- {{ ApiRef() }} {{Non-standard_header}} The **`Window.scrollByLines()`** method scrolls the document by the specified number of lines. ## Syntax ```js-nolint scrollByLines(lines) ``` ### Parameters - `lines` is the number of lines to scroll the document by. It may be a positive or negative integer. ### Return value None ({{jsxref("undefined")}}). ## Examples ```html <!-- Scroll up the document by 5 lines --> <button id="scroll-up" onclick="scrollByLines(-5);">Up 5 lines</button> <!-- Scroll down the document by 5 lines --> <button id="scroll-down" onclick="scrollByLines(5);">Down 5 lines</button> ``` ## Specifications This is not part of any specification. ## Browser compatibility {{Compat}} ## See also - {{domxref("window.scroll()")}} - {{domxref("window.scrollBy()")}} - {{domxref("window.scrollByPages()")}} - {{domxref("window.scrollTo()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/navigator/index.md
--- title: "Window: navigator property" short-title: navigator slug: Web/API/Window/navigator page-type: web-api-instance-property browser-compat: api.Window.navigator --- {{APIRef}} The **`Window.navigator`** read-only property returns a reference to the {{domxref("Navigator")}} object, which has methods and properties about the application running the script. ## Value The {{domxref("navigator")}} object. ## Examples ### Example 1: Browser detect and return a string ```js function getBrowserName(userAgent) { // The order matters here, and this may report false positives for unlisted browsers. if (userAgent.includes("Firefox")) { // "Mozilla/5.0 (X11; Linux i686; rv:104.0) Gecko/20100101 Firefox/104.0" return "Mozilla Firefox"; } else if (userAgent.includes("SamsungBrowser")) { // "Mozilla/5.0 (Linux; Android 9; SAMSUNG SM-G955F Build/PPR1.180610.011) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/9.4 Chrome/67.0.3396.87 Mobile Safari/537.36" return "Samsung Internet"; } else if (userAgent.includes("Opera") || userAgent.includes("OPR")) { // "Mozilla/5.0 (Macintosh; Intel Mac OS X 12_5_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36 OPR/90.0.4480.54" return "Opera"; } else if (userAgent.includes("Edge")) { // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299" return "Microsoft Edge (Legacy)"; } else if (userAgent.includes("Edg")) { // "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36 Edg/104.0.1293.70" return "Microsoft Edge (Chromium)"; } else if (userAgent.includes("Chrome")) { // "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36" return "Google Chrome or Chromium"; } else if (userAgent.includes("Safari")) { // "Mozilla/5.0 (iPhone; CPU iPhone OS 15_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Mobile/15E148 Safari/604.1" return "Apple Safari"; } else { return "unknown"; } } const browserName = getBrowserName(navigator.userAgent); console.log(`You are using: ${browserName}`); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/back/index.md
--- title: "Window: back() method" short-title: back() slug: Web/API/Window/back page-type: web-api-instance-method status: - deprecated - non-standard --- {{APIRef}}{{ Non-standard_header() }}{{deprecated_header}} The obsolete and non-standard method `back()` on the {{domxref("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 {{domxref("history.back")}} method instead. ## Syntax ```js-nolint back() ``` ### Parameters None. ### Return value None ({{jsxref("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 - {{domxref("History.back()")}} - {{domxref("History.forward()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/resize_event/index.md
--- title: "Window: resize event" short-title: resize slug: Web/API/Window/resize_event page-type: web-api-event browser-compat: api.Window.resize_event --- {{APIRef}} The **`resize`** event fires when the document view (window) has been resized. This event is not cancelable and does not bubble. In some earlier browsers it was possible to register `resize` event handlers on any HTML element. It is still possible to set `onresize` attributes or use {{domxref("EventTarget.addEventListener", "addEventListener()")}} to set a handler on any element. However, `resize` events are only fired on the {{domxref("Window", "window")}} object (i.e. returned by {{domxref("document.defaultView")}}). Only handlers registered on the `window` object will receive `resize` events. While the `resize` event fires only for the window nowadays, you can get resize notifications for other elements using the [ResizeObserver](/en-US/docs/Web/API/ResizeObserver) API. If the resize event is triggered too many times for your application, see [Optimizing window.onresize](https://web.archive.org/web/20220714020647/https://bencentra.com/code/2015/02/27/optimizing-window-resize.html) to control the time after which the event fires. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("resize", (event) => {}); onresize = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples ### Window size logger The following example reports the window size each time it is resized. #### 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 reportWindowSize() { heightOutput.textContent = window.innerHeight; widthOutput.textContent = window.innerWidth; } window.onresize = reportWindowSize; ``` #### Result {{EmbedLiveSample("Window_size_logger")}} > **Note:** The example output here is in an {{HTMLElement("iframe")}}, so the reported width and height values are for the `<iframe>`, not the window that this page is in. In particular, it will be hard to adjust the window size so as to see a difference in the reported height. > > The effect is easier to see if you [view the example in its own window](https://yari-demos.prod.mdn.mozit.cloud/en-US/docs/Web/API/Window/resize_event/_sample_.window_size_logger.html). ### addEventListener equivalent You could set up the event handler using the [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js window.addEventListener("resize", reportWindowSize); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/customelements/index.md
--- title: "Window: customElements property" short-title: customElements slug: Web/API/Window/customElements page-type: web-api-instance-property browser-compat: api.Window.customElements --- {{APIRef("Web Components")}} The **`customElements`** read-only property of the {{domxref("Window")}} interface returns a reference to the {{domxref("CustomElementRegistry")}} object, which can be used to register new [custom elements](/en-US/docs/Web/API/Web_components/Using_custom_elements) and get information about previously registered custom elements. ## Examples The most common example you'll see of this property being used is to get access to the {{domxref("CustomElementRegistry.define()")}} method to define and register a new custom element, e.g.: ```js let customElementRegistry = window.customElements; customElementRegistry.define("my-custom-element", MyCustomElement); ``` However, it is usually shortened to something like the following: ```js customElements.define( "element-details", class extends HTMLElement { constructor() { super(); const template = document.getElementById( "element-details-template", ).content; const shadowRoot = this.attachShadow({ mode: "open" }).appendChild( template.cloneNode(true), ); } }, ); ``` See our [web-components-examples](https://github.com/mdn/web-components-examples/) repo for more usage examples. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/alert/index.md
--- title: "Window: alert() method" short-title: alert() slug: Web/API/Window/alert page-type: web-api-instance-method browser-compat: api.Window.alert --- {{ APIRef }} `window.alert()` instructs the browser to display a dialog with an optional message, and to wait until the user dismisses the dialog. Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to dismiss the dialog. ## Syntax ```js-nolint alert() alert(message) ``` ### Parameters - `message` {{optional_inline}} - : A string you want to display in the alert dialog, or, alternatively, an object that is converted into a string and displayed. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js window.alert("Hello world!"); alert("Hello world!"); ``` Both produce: ![Black alert dialog box. At the top left small circle icon follow by white open and close square brackets containing this white text: JavaScript application. Below on the left, a Hello world! white text. And on the bottom right a small blue button. The button's text is: ok in black.](alerthelloworld.png) ## Notes The alert dialog should be used for messages which do not require any response on the part of the user, other than the acknowledgement of the message. Dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window). Alternatively {{HTMLElement("dialog")}} element can be used to display alerts. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{HTMLElement("dialog")}} element - {{domxref("window.confirm","confirm")}} - {{domxref("window.prompt","prompt")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/gamepadconnected_event/index.md
--- title: "Window: gamepadconnected event" short-title: gamepadconnected slug: Web/API/Window/gamepadconnected_event page-type: web-api-event browser-compat: api.Window.gamepadconnected_event --- {{APIRef}} The `gamepadconnected` event is fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used. The event will not fire if disallowed by the document's {{httpheader('Permissions-Policy/gamepad','gamepad')}} [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy). This event is not cancelable and does not bubble. ## Examples To be informed when a gamepad is connected, you can add a handler to the window using {{domxref("EventTarget.addEventListener", "addEventListener()")}}, like this: ```js window.addEventListener("gamepadconnected", (event) => { // All buttons and axes values can be accessed through const gamepad = event.gamepad; }); ``` Alternatively, you can use the `window.ongamepadconnected` event handler property to establish a handler for the `gamepadconnected` event: ```js window.ongamepadconnected = (event) => { // All buttons and axes values can be accessed through const gamepad = event.gamepad; }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [gamepaddisconnected](/en-US/docs/Web/API/Window/gamepaddisconnected_event) - [Using Gamepad API](/en-US/docs/Web/API/Gamepad_API/Using_the_Gamepad_API)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/speechsynthesis/index.md
--- title: "Window: speechSynthesis property" short-title: speechSynthesis slug: Web/API/Window/speechSynthesis page-type: web-api-instance-property browser-compat: api.Window.speechSynthesis --- {{APIRef()}} The `speechSynthesis` read-only property of the Window object returns a {{domxref("SpeechSynthesis")}} object, which is the entry point into using [Web Speech API](/en-US/docs/Web/API/Web_Speech_API) speech synthesis functionality. ## Value A {{domxref("SpeechSynthesis")}} object. ## Examples In our basic [Speech synthesizer demo](https://github.com/mdn/dom-examples/tree/main/web-speech-api/speak-easy-synthesis), we first grab a reference to the SpeechSynthesis controller using `window.speechSynthesis`. After defining some necessary variables, we retrieve a list of the voices available using {{domxref("SpeechSynthesis.getVoices()")}} and populate a select menu with them so the user can choose what voice they want. Inside the `inputForm.onsubmit` handler, we stop the form submitting with [preventDefault()](/en-US/docs/Web/API/Event/preventDefault), create a new {{domxref("SpeechSynthesisUtterance")}} instance containing the text from the text {{htmlelement("input")}}, set the utterance's voice to the voice selected in the {{htmlelement("select")}} element, and start the utterance speaking via the {{domxref("SpeechSynthesis.speak()")}} method. ```js const synth = window.speechSynthesis; const inputForm = document.querySelector("form"); const inputTxt = document.querySelector("input"); const voiceSelect = document.querySelector("select"); function populateVoiceList() { voices = synth.getVoices(); for (const voice of voices) { const option = document.createElement("option"); option.textContent = `${voice.name} (${voice.lang})`; if (voice.default) { option.textContent += " — DEFAULT"; } option.setAttribute("data-lang", voice.lang); option.setAttribute("data-name", voice.name); voiceSelect.appendChild(option); } } populateVoiceList(); if (speechSynthesis.onvoiceschanged !== undefined) { speechSynthesis.onvoiceschanged = populateVoiceList; } inputForm.onsubmit = (event) => { event.preventDefault(); const utterThis = new SpeechSynthesisUtterance(inputTxt.value); const selectedOption = voiceSelect.selectedOptions[0].getAttribute("data-name"); utterThis.voice = voices.find((v) => v.name === selectedOption); synth.speak(utterThis); inputTxt.blur(); }; ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Web Speech API](/en-US/docs/Web/API/Web_Speech_API)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/personalbar/index.md
--- title: "Window: personalbar property" short-title: personalbar slug: Web/API/Window/personalbar page-type: web-api-instance-property browser-compat: api.Window.personalbar --- {{APIRef}} 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` {{ReadOnlyInline}} - : A boolean property, `false` if this `Window` is a popup, and `true` otherwise. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.locationbar")}} - {{domxref("window.menubar")}} - {{domxref("window.scrollbars")}} - {{domxref("window.statusbar")}} - {{domxref("window.toolbar")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/clearimmediate/index.md
--- title: "Window: clearImmediate() method" short-title: clearImmediate() slug: Web/API/Window/clearImmediate page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.Window.clearImmediate --- {{APIRef("HTML DOM")}} {{deprecated_header}}{{non-standard_header}} This method clears the action specified by {{DOMxRef("window.setImmediate")}}. ## Syntax ```js-nolint clearImmediate(immediateID) ``` ### Parameters - `immediateID` - : The ID returned by {{DOMxRef("window.setImmediate")}}. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js let immediateID = setImmediate(() => { // Run some code }); document.getElementById("button").addEventListener(() => { clearImmediate(immediateID); }); ``` ## Specifications Not part of any current specifications. The [Efficient Script Yielding](https://w3c.github.io/setImmediate/#si-setImmediate) specification is no longer being worked on. ## Browser compatibility {{Compat}} ## See also - [Polyfill of `clearImmediate` in `core-js`](https://github.com/zloirock/core-js#setimmediate) - {{DOMxRef("Window.setImmediate()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/focus_event/index.md
--- title: "Window: focus event" short-title: focus slug: Web/API/Window/focus_event page-type: web-api-event browser-compat: api.Window.focus_event --- {{APIRef}} The **`focus`** event fires when an element has received focus. The opposite of `focus` is {{domxref("Window/blur_event", "blur")}}. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("focus", (event) => {}); onfocus = (event) => {}; ``` ## Event type A {{domxref("FocusEvent")}}. Inherits from {{domxref("UIEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("FocusEvent")}} ## Event properties _This interface also inherits properties from its parent {{domxref("UIEvent")}}, and indirectly from {{domxref("Event")}}._ - {{domxref("FocusEvent.relatedTarget")}} - : An {{domxref("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 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} to monitor `focus` and {{domxref("Window/blur_event", "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 {{EmbedLiveSample("Live_example")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related event: {{domxref("Window/blur_event", "blur")}} - This event on `Element` targets: {{domxref("Element/focus_event", "focus")}} event
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/setresizable/index.md
--- title: "Window: setResizable() method" short-title: setResizable() slug: Web/API/Window/setResizable page-type: web-api-instance-method status: - deprecated - non-standard browser-compat: api.Window.setResizable --- {{APIRef("HTML DOM")}} {{deprecated_header}}{{non-standard_header}} This method does nothing; it is a no-op. It is solely kept for compatibility with Netscape 4.x. ## Syntax ```js-nolint setResizable() ``` ### Return value None ({{jsxref("undefined")}}). ## Specifications Not part of any current specifications. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/screenx/index.md
--- title: "Window: screenX property" short-title: screenX slug: Web/API/Window/screenX page-type: web-api-instance-property browser-compat: api.Window.screenX --- {{APIRef}} 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 — {{domxref("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](https://mdn.github.io/dom-examples/screenleft-screentop/) ([source code](https://github.com/mdn/dom-examples/blob/main/screenleft-screentop/index.html)) example, you'll see a canvas onto which has been drawn a circle. In this example we are using {{domxref("Window.screenLeft")}}/{{domxref("Window.screenTop")}} plus {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.screenLeft")}} - {{domxref("Window.screenY")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/querylocalfonts/index.md
--- title: "Window: queryLocalFonts() method" short-title: queryLocalFonts() slug: Web/API/Window/queryLocalFonts page-type: web-api-instance-method status: - experimental browser-compat: api.Window.queryLocalFonts --- {{APIRef("Local Font Access API")}}{{SeeCompatTable}}{{SecureContext_Header}} The **`window.queryLocalFonts()`** method returns a {{jsxref("Promise")}} that fulfills with an array of {{domxref("FontData")}} objects representing the font faces available locally. To use this method, the user must grant permission to access `local-fonts` (permission status can be queried via the {{domxref("Permissions API", "", "", "nocode")}}). In addition, this feature may be blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy) set on your server. ## Syntax ```js-nolint queryLocalFonts(options) ``` ### Parameters - `options` {{optional_inline}} - : Contains optional configuration parameters. Currently only one property is defined: - `postscriptNames` {{optional_inline}} - : An array of font PostScript names. If this is specified, only fonts with PostScript names matching those in the array will be included in the results; if not, all fonts will be included in the results. ### Return value A {{jsxref("Promise")}} that fulfills with an array of {{domxref("FontData")}} objects representing the font faces available locally. ### Exceptions - `NotAllowedError` {{domxref("DOMException")}} - : The user chose to deny permission to use this feature when presented with the browser's permission prompt after the method was first invoked. - `SecurityError` {{domxref("DOMException")}} - : Use of this feature was blocked by a [Permissions Policy](/en-US/docs/Web/HTTP/Permissions_Policy), or it was not called via a user interaction such as a button press, or current {{glossary("origin")}} is an opaque origin. ## Examples For a working live demo, see [Font Select Demo](https://local-font-access.glitch.me/demo/). ### Font enumeration The following snippet will query for all available fonts and log metadata. This could be used, for example, to populate a font picker control. ```js async function logFontData() { try { const availableFonts = await window.queryLocalFonts(); for (const fontData of availableFonts) { console.log(fontData.postscriptName); console.log(fontData.fullName); console.log(fontData.family); console.log(fontData.style); } } catch (err) { console.error(err.name, err.message); } } ``` ### Limiting returned results To limit the returned font data to only a specific list of font faces, use the `postscriptNames` option. ```js async function returnSpecificFonts() { const availableFonts = await window.queryLocalFonts({ postscriptNames: ["Verdana", "Verdana-Bold", "Verdana-Italic"], }); return availableFonts; } ``` ### Accessing low-level data The {{domxref("FontData.blob", "blob()")}} method provides access to low-level [SFNT](https://en.wikipedia.org/wiki/SFNT) data — this is a font file format that can contain other font formats, such as PostScript, TrueType, OpenType, or Web Open Font Format (WOFF). ```js async function computeOutlineFormat() { try { const availableFonts = await window.queryLocalFonts({ postscriptNames: ["ComicSansMS"], }); for (const fontData of availableFonts) { // `blob()` returns a Blob containing valid and complete // SFNT-wrapped font data. const sfnt = await fontData.blob(); // Slice out only the bytes we need: the first 4 bytes are the SFNT // version info. // Spec: https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font const sfntVersion = await sfnt.slice(0, 4).text(); let outlineFormat = "UNKNOWN"; switch (sfntVersion) { case "\x00\x01\x00\x00": case "true": case "typ1": outlineFormat = "truetype"; break; case "OTTO": outlineFormat = "cff"; break; } console.log("Outline format:", outlineFormat); } } catch (err) { console.error(err.name, err.message); } } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Local Font Access API", "Local Font Access API", "", "nocode")}} - [Use advanced typography with local fonts](https://developer.chrome.com/docs/capabilities/web-apis/local-fonts) - {{cssxref("@font-face")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/toolbar/index.md
--- title: "Window: toolbar property" short-title: toolbar slug: Web/API/Window/toolbar page-type: web-api-instance-property browser-compat: api.Window.toolbar --- {{APIRef}} Returns the `toolbar` object. This is one of a group of `Window` properties that contain a boolean `visible` property, that used to represent whether or not a particular part of a web browser's user interface was visible. For privacy and interoperability reasons, the value of the `visible` property is now `false` if this `Window` is a popup, and `true` otherwise. ## Value An object containing a single property: - `visible` {{ReadOnlyInline}} - : A boolean property, `false` if this `Window` is a popup, and `true` otherwise. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.locationbar")}} - {{domxref("window.menubar")}} - {{domxref("window.personalbar")}} - {{domxref("window.scrollbars")}} - {{domxref("window.statusbar")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/scrolly/index.md
--- title: "Window: scrollY property" short-title: scrollY slug: Web/API/Window/scrollY page-type: web-api-instance-property browser-compat: api.Window.scrollY --- {{APIRef("CSSOM View")}} The read-only **`scrollY`** property of the {{domxref("Window")}} interface returns the number of pixels that the document is currently scrolled vertically. This value is subpixel precise in modern browsers, meaning that it isn't necessarily a whole number. You can get the number of pixels the document is scrolled horizontally from the {{domxref("Window.scrollX", "scrollX")}} property. ## Value In practice, the returned value is a double-precision floating-point value with the range of 2^(-1022) to 2^(+1023). It indicates the number of pixels the document is currently scrolled vertically from the origin, where a positive value means the content is scrolled to upward. If the document is rendered on a subpixel-precise device, then the returned value is also subpixel-precise and may contain a decimal component. If the document isn't scrolled at all up or down, then `scrollY` is 0. > **Note:** If you need an integer value, you can use {{jsxref("Math.round()")}} to round it off. In more technical terms, `scrollY` returns the Y coordinate of the top edge of the current {{Glossary("viewport")}}. If there is no viewport, the returned value is 0\. ## Examples ```js // make sure and go down to the second page if (window.scrollY) { window.scroll(0, 0); // reset the scroll position to the top left of the document. } window.scrollByPages(1); ``` ## Notes Use this property to check that the document hasn't already been scrolled when using relative scroll functions such as {{domxref("window.scrollBy", "scrollBy()")}}, {{domxref("window.scrollByLines", "scrollByLines()")}}, or {{domxref("window.scrollByPages", "scrollByPages()")}}. The `pageYOffset` property is an alias for the `scrollY` property: ```js window.pageYOffset === window.scrollY; // always true ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.scrollX")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/cancelanimationframe/index.md
--- title: "Window: cancelAnimationFrame() method" short-title: cancelAnimationFrame() slug: Web/API/Window/cancelAnimationFrame page-type: web-api-instance-method browser-compat: api.Window.cancelAnimationFrame --- {{APIRef}} The **`window.cancelAnimationFrame()`** method cancels an animation frame request previously scheduled through a call to {{domxref("window.requestAnimationFrame()")}}. ## Syntax ```js-nolint cancelAnimationFrame(requestID) ``` ### Parameters - `requestID` - : The ID value returned by the call to {{domxref("window.requestAnimationFrame()")}} that requested the callback. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js const requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; const cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame; const start = Date.now(); let myReq; function step(timestamp) { const progress = timestamp - start; d.style.left = `${Math.min(progress / 10, 200)}px`; if (progress < 2000) { // it's important to update the requestId each time you're calling requestAnimationFrame myReq = requestAnimationFrame(step); } } myReq = requestAnimationFrame(step); // the cancellation uses the last requestId cancelAnimationFrame(myReq); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window.requestAnimationFrame()")}} - {{domxref("DedicatedWorkerGlobalScope.cancelAnimationFrame()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/requestanimationframe/index.md
--- title: "Window: requestAnimationFrame() method" short-title: requestAnimationFrame() slug: Web/API/window/requestAnimationFrame page-type: web-api-instance-method browser-compat: api.Window.requestAnimationFrame --- {{APIRef}} The **`window.requestAnimationFrame()`** method tells the browser you wish to perform an animation. It requests the browser to call a user-supplied callback function before the next repaint. The frequency of calls to the callback function will generally match the display refresh rate. The most common refresh rate is 60hz, (60 cycles/frames per second), though 75hz, 120hz, and 144hz are also widely used. `requestAnimationFrame()` calls are paused in most browsers when running in background tabs or hidden {{ HTMLElement("iframe") }}s, in order to improve performance and battery life. > **Note:** Your callback function must call `requestAnimationFrame()` again if > you want to animate another frame. `requestAnimationFrame()` is one-shot. > **Warning:** Be sure always to use the first argument (or some other method for > getting the current time) to calculate how much the animation will progress in > a frame — **otherwise, the animation will run faster on high refresh-rate screens**. > For ways to do that, see the examples below. ## Syntax ```js-nolint requestAnimationFrame(callback) ``` ### Parameters - `callback` - The function to call when it's time to update your animation for the next repaint. This callback function is passed a single argument: a {{domxref("DOMHighResTimeStamp")}} indicating the end time of the previous frame's rendering (based on the number of milliseconds since [time origin](/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin)). - The timestamp is a decimal number, in milliseconds, but with a minimal precision of 1 millisecond. For `Window` objects (not `Workers`), it is equal to {{domxref("AnimationTimeline/currentTime", "document.timeline.currentTime")}}. This timestamp is shared between all windows that run on the same agent (all same-origin windows and, more importantly, same-origin iframes) — which allows synchronizing animations across multiple `requestAnimationFrame` callbacks. The timestamp value is also similar to calling {{domxref('performance.now()')}} at the start of the callback function, but it is never the same value. - When multiple callbacks queued by `requestAnimationFrame()` begin to fire in a single frame, each receives the same timestamp even though time has passed during the computation of every previous callback's workload. ### Return value A `long` integer value, the request ID, that uniquely identifies the entry in the callback list. This is a non-zero value, but you may not make any other assumptions about its value. You can pass this value to {{domxref("window.cancelAnimationFrame()")}} to cancel the refresh callback request. ## Examples In this example, an element is animated for 2 seconds (2000 milliseconds). The element moves at a speed of 0.1px/ms to the right, so its relative position (in CSS pixels) can be calculated in function of the time elapsed since the start of the animation (in milliseconds) with `0.1 * elapsed`. The element's final position is 200px (`0.1 * 2000`) to the right of its initial position. ```js const element = document.getElementById("some-element-you-want-to-animate"); let start, previousTimeStamp; let done = false; function step(timeStamp) { if (start === undefined) { start = timeStamp; } const elapsed = timeStamp - start; if (previousTimeStamp !== timeStamp) { // Math.min() is used here to make sure the element stops at exactly 200px const count = Math.min(0.1 * elapsed, 200); element.style.transform = `translateX(${count}px)`; if (count === 200) done = true; } if (elapsed < 2000) { // Stop the animation after 2 seconds previousTimeStamp = timeStamp; if (!done) { window.requestAnimationFrame(step); } } } window.requestAnimationFrame(step); ``` The following three examples illustrate different approaches to setting the zero point in time, the baseline for calculating the progress of your animation in each frame. If you want to synchronize to an external clock, such as {{domxref("BaseAudioContext.currentTime")}}, the highest precision available is the duration of a single frame, 16.67ms @60hz. The callback's timestamp argument represents the end of the previous frame, so the soonest your newly calculated value(s) will be rendered is in the next frame. This example waits until the first callback executes to set `zero`. If your animation jumps to a new value when it starts, you must structure it this way. If you do not need to synchronize to anything external, such as audio, then this approach is recommended because some browsers have a multi-frame delay between the initial call to `requestAnimationFrame()` and the first call to the callback function. ```js let zero; requestAnimationFrame(firstFrame); function firstFrame(timeStamp) { zero = timeStamp; animate(timeStamp); } function animate(timeStamp) { const value = (timeStamp - zero) / duration; if (value < 1) { element.style.opacity = value; requestAnimationFrame((t) => animate(t)); } else element.style.opacity = 1; } ``` This example uses {{domxref("AnimationTimeline/currentTime", "document.timeline.currentTime")}} to set a zero value before the first call to `requestAnimationFrame`. `document.timeline.currentTime` aligns with the `timeStamp` argument, so the zero value is equivalent to the 0th frame's timestamp. ```js const zero = document.timeline.currentTime; requestAnimationFrame(animate); function animate(timeStamp) { const value = (timeStamp - zero) / duration; // animation-timing-function: linear if (value < 1) { element.style.opacity = value; requestAnimationFrame((t) => animate(t)); } else element.style.opacity = 1; } ``` This example animates using {{domxref("performance.now()")}} instead of the callback's timestamp value. You might use this to achieve slightly higher synchronization precision, though the extra degree of precision is variable and not much of an increase. Note: This example does not allow you to synchronize animation callbacks reliably. ```js const zero = performance.now(); requestAnimationFrame(animate); function animate() { const value = (performance.now() - zero) / duration; if (value < 1) { element.style.opacity = value; requestAnimationFrame((t) => animate(t)); } else element.style.opacity = 1; } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Window.cancelAnimationFrame()")}} - {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()")}} - [Animating with JavaScript: from setInterval to requestAnimationFrame](https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/) - Blog post - [TestUFO: Test your web browser for requestAnimationFrame() Timing Deviations](https://www.testufo.com/#test=animation-time-graph)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/popstate_event/index.md
--- title: "Window: popstate event" short-title: popstate slug: Web/API/Window/popstate_event page-type: web-api-event browser-compat: api.Window.popstate_event --- {{APIRef("History API")}} The **`popstate`** event of the {{domxref("Window")}} interface is fired when the active history entry changes while the user navigates the session history. It changes the current history entry to that of the last page the user visited or, if {{domxref("history.pushState()")}} has been used to add a history entry to the history stack, that history entry is used instead. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("popstate", (event) => {}); onpopstate = (event) => {}; ``` ## Event type A {{domxref("PopStateEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PopStateEvent")}} ## Event properties - {{domxref("PopStateEvent.state")}} {{ReadOnlyInline}} - : Returns a copy of the information that was provided to `pushState()` or `replaceState()`. ## Event handler aliases In addition to the `Window` interface, the event handler property `onpopstate` is also available on the following elements: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("SVGSVGElement")}} ## The history stack If the history entry being activated was created by a call to [`history.pushState()`](/en-US/docs/Web/API/History/pushState) or was affected by a call to [`history.replaceState()`](/en-US/docs/Web/API/History/replaceState), the `popstate` event's `state` property contains a copy of the history entry's state object. These methods and their corresponding events can be used to add data to the history stack which can be used to reconstruct a dynamically generated page, or to otherwise alter the state of the content being presented while remaining on the same {{domxref("Document")}}. Note that just calling `history.pushState()` or `history.replaceState()` won't trigger a `popstate` event. The `popstate` event will be triggered by doing a browser action such as a click on the back or forward button (or calling `history.back()` or `history.forward()` in JavaScript). Browsers tend to handle the `popstate` event differently on page load. Chrome (prior to v34) and Safari always emit a `popstate` event on page load, but Firefox doesn't. > **Note:** When writing functions that process `popstate` event it is important to take into account that properties like `window.location` will already reflect the state change (if it affected the current URL), but `document` might still not. If the goal is to catch the moment when the new document state is already fully in place, a zero-delay {{domxref("setTimeout()")}} method call should be used to effectively put its inner _callback_ function that does the processing at the end of the browser event loop: `window.onpopstate = () => setTimeout(doSomeThing, 0);` ## When popstate is sent It's important to first understand that — to combat unwanted pop-ups — browsers may not fire the `popstate` event at all unless the page has been interacted with. This section describes the steps that browsers follow in the cases where they _do_ potentially fire the `popstate` event (that is, in the cases where the page has been interacted with). When a navigation occurs — either due to the user triggering the browser's <kbd>Back</kbd> button or otherwise — the `popstate` event is near the end of the process to navigate to the new location. It happens after the new location has loaded (if needed), displayed, made visible, and so on — after the {{domxref("Window.pageshow_event", "pageshow")}} event is sent, but before the persisted user state information is restored and the {{domxref("Window.hashchange_event", "hashchange")}} event is sent. To better understand when the `popstate` event is fired, consider this simplified sequence of events that occurs when the current history entry changes due to either the user navigating the site or the history being traversed programmatically. Here, the transition is changing the current history entry to one we'll refer to as **new-entry**. The current page's session history stack entry will be referred to as **current-entry**. 1. If **new-entry** doesn't currently contain an existing {{domxref("Document")}}, fetch the content and create its `Document` before continuing. This will eventually send events such as {{domxref("Document.DOMContentLoaded_event", "DOMContentLoaded")}} and {{domxref("Window.load_event", "load")}} to the {{domxref("Window")}} containing the document, but the steps below will continue to execute in the meantime. 2. If **current-entry**'s title wasn't set using one of the History API methods ({{domxref("History.pushState", "pushState()")}} or {{domxref("History.replaceState", "replaceState()")}}), set the entry's title to the string returned by its {{domxref("document.title")}} attribute. 3. If the browser has state information it wishes to store with the **current-entry** before navigating away from it, it then does so. The entry is now said to have "persisted user state." This information the browser might add to the history session entry may include, for instance, the document's scroll position, the values of form inputs, and other such data. 4. If **new-entry** has a different `Document` object than **current-entry**, the browsing context is updated so that its {{domxref("Window.document", "document")}} property refers to the document referred to by **new-entry**, and the context's name is updated to match the context name of the now-current document. 5. Each form control within **new-entry**'s {{domxref("Document")}} that has [`autocomplete`](/en-US/docs/Web/HTML/Element/input#autocomplete) configured with its autofill field name set to `off` is reset. See [The HTML autocomplete attribute](/en-US/docs/Web/HTML/Attributes/autocomplete) for more about the autocomplete field names and how autocomplete works. 6. If **new-entry**'s document is already fully loaded and ready—that is, its {{domxref("Document.readyState", "readyState")}} is `complete`—and the document is not already visible, it's made visible and the {{domxref("Window.pageshow_event", "pageshow")}} event is fired at the document with the {{domxref("PageTransitionEvent")}}'s {{domxref("PageTransitionEvent.persisted", "persisted")}} attribute set to `true`. 7. The document's {{domxref("Document.URL", "URL")}} is set to that of **new-entry**. 8. If the history traversal is being performed with replacement enabled, the entry immediately prior to the destination entry (taking into account the `delta` parameter on methods such as {{domxref("History.go", "go()")}}) is removed from the history stack. 9. If the **new-entry** doesn't have persisted user state and its URL's fragment is non-`null`, the document is scrolled to that fragment. 10. Next, **current-entry** is set to **new-entry**. The destination entry is now considered to be current. 11. If **new-entry** has serialized state information saved with it, that information is deserialized into {{domxref("History.state")}}; otherwise, `state` is `null`. 12. If the value of `state` changed, the `popstate` event is sent to the document. 13. Any persisted user state is restored, if the browser chooses to do so. 14. If the original and new entries shared the same document, but had different fragments in their URLs, send the {{domxref("Window.hashchange_event", "hashchange")}} event to the window. As you can see, the `popstate` event is nearly the last thing done in the process of navigating pages in this way. ## Examples A page at `http://example.com/example.html` running the following code will generate logs as indicated: ```js window.addEventListener("popstate", (event) => { console.log( `location: ${document.location}, state: ${JSON.stringify(event.state)}`, ); }); history.pushState({ page: 1 }, "title 1", "?page=1"); history.pushState({ page: 2 }, "title 2", "?page=2"); history.replaceState({ page: 3 }, "title 3", "?page=3"); history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // Logs "location: http://example.com/example.html, state: null" history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}" ``` The same example using the `onpopstate` event handler property: ```js window.onpopstate = (event) => { console.log( `location: ${document.location}, state: ${JSON.stringify(event.state)}`, ); }; history.pushState({ page: 1 }, "title 1", "?page=1"); history.pushState({ page: 2 }, "title 2", "?page=2"); history.replaceState({ page: 3 }, "title 3", "?page=3"); history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}" history.back(); // Logs "location: http://example.com/example.html, state: null" history.go(2); // Logs "location: http://example.com/example.html?page=3, state: {"page":3}" ``` Note that even though the original history entry (for `http://example.com/example.html`) has no state object associated with it, a `popstate` event is still fired when we activate that entry after the second call to `history.back()`. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Manipulating the browser history (the History API)](/en-US/docs/Web/API/History_API) - [Window: `hashchange` event](/en-US/docs/Web/API/Window/hashchange_event)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/vrdisplaydeactivate_event/index.md
--- title: "Window: vrdisplaydeactivate event" short-title: vrdisplaydeactivate slug: Web/API/Window/vrdisplaydeactivate_event page-type: web-api-event status: - deprecated - non-standard browser-compat: api.Window.vrdisplaydeactivate_event --- {{APIRef("Window")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`vrdisplaydeactivate`** event of the [WebVR API](/en-US/docs/Web/API/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](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("vrdisplaydeactivate", (event) => {}); onvrdisplaydeactivate = (event) => {}; ``` ## Event type A {{domxref("VRDisplayEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("VRDisplayEvent")}} ## Event properties _`VRDisplayEvent` also inherits properties from its parent object, {{domxref("Event")}}._ - {{domxref("VRDisplayEvent.display")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : The {{domxref("VRDisplay")}} associated with this event. - {{domxref("VRDisplayEvent.reason")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : A human-readable reason why the event was fired. ## Examples You can use the `vrdisplaydeactivate` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/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](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard. Until all browsers have implemented the new [WebXR Device API](https://immersive-web.github.io/webxr/), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/). ## Browser compatibility {{Compat}} ## See also - [WebVR API](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/self/index.md
--- title: "Window: self property" short-title: self slug: Web/API/Window/self page-type: web-api-instance-property browser-compat: api.Window.self --- {{APIRef}} The **`Window.self`** read-only property returns the window itself, as a {{glossary("WindowProxy")}}. It can be used with dot notation on a `window` object (that is, `window.self`) or standalone (`self`). The advantage of the standalone notation is that a similar notation exists for non-window contexts, such as in {{domxref("Worker", "Web Workers", "", 1)}}. By using `self`, you can refer to the global scope in a way that will work not only in a window context (`self` will resolve to `window.self`) but also in a worker context (`self` will then resolve to {{domxref("WorkerGlobalScope.self")}}). ## Value A {{glossary("WindowProxy")}} object. ## Examples Uses of `window.self` like the following could just as well be replaced by `window`. ```js if (window.parent.frames[0] !== window.self) { // this window is not the first frame in the list } ``` Furthermore, when executing in the active document of a browsing context, `window` is a reference to the current global object and thus all of the following are equivalent: ```js const w1 = window; const w2 = self; const w3 = window.window; const w4 = window.self; // w1, w2, w3, w4 all strictly equal, but only w2 will function in workers ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Its `Worker` equivalent, {{domxref("WorkerGlobalScope.self")}}.
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/moveby/index.md
--- title: "Window: moveBy() method" short-title: moveBy() slug: Web/API/Window/moveBy page-type: web-api-instance-method browser-compat: api.Window.moveBy --- {{APIRef}} The **`moveBy()`** method of the {{domxref("Window")}} interface moves the current window by a specified amount. > **Note:** This function moves the window relative to its current > location. In contrast, {{domxref("window.moveTo()")}} moves the window to an absolute > location. ## Syntax ```js-nolint moveBy(deltaX, deltaY) ``` ### Parameters - `deltaX` is the amount of pixels to move the window horizontally. Positive values are to the right, while negative values are to the left. - `deltaY` is the amount of pixels to move the window vertically. Positive values are down, while negative values are up. ### Return value None ({{jsxref("undefined")}}). ## Examples This example moves the window 10 pixels to the right and 10 pixels up. ```js function budge() { moveBy(10, -10); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} As of Firefox 7, websites can no longer move a browser window [in the following cases](https://bugzil.la/565541#c24): 1. You can't move a window or tab that wasn't created by {{domxref("Window.open()")}}. 2. You can't move a window or tab when it's in a window with more than one tab. ## See also - {{domxref("Window.moveTo()")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/getscreendetails/index.md
--- title: "Window: getScreenDetails() method" short-title: getScreenDetails() slug: Web/API/Window/getScreenDetails page-type: web-api-instance-method status: - experimental browser-compat: api.Window.getScreenDetails --- {{APIRef("Window Management API")}}{{SeeCompatTable}}{{securecontext_header}} The **`getScreenDetails()`** method of the {{domxref("Window")}} interface returns a {{jsxref("Promise")}} that fulfills with a {{domxref("ScreenDetails")}} object instance representing the details of all the screens available to the user's device. ## Syntax ```js-nolint getScreenDetails() ``` ### Parameters None. ### Return value A {{jsxref("Promise")}} that fulfills with a {{domxref("ScreenDetails")}} object instance. ### Exceptions - `NotAllowedError` {{domxref("DOMException")}} - : Thrown if a {{httpheader("Permissions-Policy/window-management", "window-management")}} [Permissions-Policy](/en-US/docs/Web/HTTP/Permissions_Policy) is set that blocks use of the [Window Management API](/en-US/docs/Web/API/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 {{domxref("Permissions.query()")}} to query `window-management`). Provided they grant permission, the resulting {{domxref("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](https://mdn.github.io/dom-examples/window-management-api/) for a full example (see the [source code](https://github.com/mdn/dom-examples/tree/main/window-management-api) also). ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Window Management API](/en-US/docs/Web/API/Window_Management_API)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/blur_event/index.md
--- title: "Window: blur event" short-title: blur slug: Web/API/Window/blur_event page-type: web-api-event browser-compat: api.Window.blur_event --- {{APIRef}} The **`blur`** event fires when an element has lost focus. The opposite of `blur` is {{domxref("Window/focus_event", "focus")}}. This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("blur", (event) => {}); onblur = (event) => {}; ``` ## Event type A {{domxref("FocusEvent")}}. Inherits from {{domxref("UIEvent")}} and {{domxref("Event")}}. {{InheritanceDiagram("FocusEvent")}} ## Event properties _This interface also inherits properties from its parent {{domxref("UIEvent")}}, and indirectly from {{domxref("Event")}}._ - {{domxref("FocusEvent.relatedTarget")}} - : An {{domxref("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 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} to monitor {{domxref("Window/focus_event", "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 {{EmbedLiveSample("Live_example")}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} The value of {{DOMxRef("Document.activeElement")}} varies across browsers while this event is being handled ([Firefox bug 452307](https://bugzil.la/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: {{domxref("Window/focus_event", "focus")}} - This event on `Element` targets: {{domxref("Element/blur_event", "blur")}} event
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/postmessage/index.md
--- title: "Window: postMessage() method" short-title: postMessage() slug: Web/API/Window/postMessage page-type: web-api-instance-method browser-compat: api.Window.postMessage --- {{ApiRef("HTML DOM")}} The **`window.postMessage()`** method safely enables cross-origin communication between {{domxref("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](/en-US/docs/Web/Security/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 {{domxref("MessageEvent")}} on it with `targetWindow.postMessage()`. The receiving window is then free to [handle this event](/en-US/docs/Web/Events/Event_handlers) as needed. The arguments passed to `window.postMessage()` (_i.e.,_ the "message") are [exposed to the receiving window through the event object](#the_dispatched_event). ## Syntax ```js-nolint 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 {{domxref("Web_Workers_API/Structured_clone_algorithm", "the structured clone algorithm", "", 1)}}. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. - `options` {{optional_Inline}} - : An optional object containing a `transfer` field with a sequence of [transferable objects](/en-US/docs/Web/API/Web_Workers_API/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_Inline}} - : 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_Inline}} - : A sequence of [transferable objects](/en-US/docs/Web/API/Web_Workers_API/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 ({{jsxref("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 {{Glossary("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 {{domxref("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 {{jsxref("SharedArrayBuffer")}} objects, you might need to make sure you cross-site isolated your site properly. Shared memory is gated behind two HTTP headers: - {{HTTPHeader("Cross-Origin-Opener-Policy")}} with `same-origin` as value (protects your origin from attackers) - {{HTTPHeader("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 {{domxref("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 {{domxref("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 {{domxref("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_inline}} `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 {{WebExtAPIRef("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Document.domain")}} - {{domxref("CustomEvent")}} - {{domxref("BroadcastChannel")}} - For same-origin communication.
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/vrdisplaypresentchange_event/index.md
--- title: "Window: vrdisplaypresentchange event" short-title: vrdisplaypresentchange slug: Web/API/Window/vrdisplaypresentchange_event page-type: web-api-event status: - deprecated - non-standard browser-compat: api.Window.vrdisplaypresentchange_event --- {{APIRef("Window")}}{{Deprecated_Header}}{{Non-standard_Header}} The **`vrdisplaypresentchange`** event of the [WebVR API](/en-US/docs/Web/API/WebVR_API) is fired when the presenting state of a VR display changes — i.e. goes from presenting to not presenting, or vice versa. > **Note:** This event was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/). It has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). This event is not cancelable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("vrdisplaypresentchange", (event) => {}); onvrdisplaypresentchange = (event) => {}; ``` ## Event type A {{domxref("VRDisplayEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("VRDisplayEvent")}} ## Event properties _`VRDisplayEvent` also inherits properties from its parent object, {{domxref("Event")}}._ - {{domxref("VRDisplayEvent.display")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : The {{domxref("VRDisplay")}} associated with this event. - {{domxref("VRDisplayEvent.reason")}} {{Deprecated_Inline}} {{ReadOnlyInline}} - : A human-readable reason why the event was fired. ## Examples You can use the `vrdisplaypresentchange` event in an [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) method: ```js window.addEventListener("vrdisplaypresentchange", () => { info.textContent = vrDisplay.isPresenting ? "Display has started presenting." : "Display has stopped presenting."; reportDisplays(); }); ``` Or use the `onvrdisplaypresentchange` event handler property: ```js window.onvrdisplaypresentchange = () => { info.textContent = vrDisplay.isPresenting ? "Display has started presenting." : "Display has stopped presenting."; reportDisplays(); }; ``` ## Specifications This event was part of the old [WebVR API](https://immersive-web.github.io/webvr/spec/1.1/) that has been superseded by the [WebXR Device API](https://immersive-web.github.io/webxr/). It is no longer on track to becoming a standard. Until all browsers have implemented the new [WebXR Device API](https://immersive-web.github.io/webxr/), it is recommended to rely on frameworks, like [A-Frame](https://aframe.io/), [Babylon.js](https://www.babylonjs.com/), or [Three.js](https://threejs.org/), or a [polyfill](https://github.com/immersive-web/webxr-polyfill), to develop WebXR applications that will work across all browsers [\[1\]](https://developer.oculus.com/documentation/web/port-vr-xr/). ## Browser compatibility {{Compat}} ## See also - [WebVR API](/en-US/docs/Web/API/WebVR_API)
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/message_event/index.md
--- title: "Window: message event" short-title: message slug: Web/API/Window/message_event page-type: web-api-event browser-compat: api.Window.message_event --- {{APIRef}} The `message` event is fired on a {{domxref('Window')}} object when the window receives a message, for example from a call to [`Window.postMessage()`](/en-US/docs/Web/API/Window/postMessage) from another browsing context. This event is not cancellable and does not bubble. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("message", (event) => {}); onmessage = (event) => {}; ``` ## Event type A {{domxref("MessageEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("MessageEvent")}} ## Event properties _This interface also inherits properties from its parent, {{domxref("Event")}}._ - {{domxref("MessageEvent.data")}} {{ReadOnlyInline}} - : The data sent by the message emitter. - {{domxref("MessageEvent.origin")}} {{ReadOnlyInline}} - : A string representing the origin of the message emitter. - {{domxref("MessageEvent.lastEventId")}} {{ReadOnlyInline}} - : A string representing a unique ID for the event. - {{domxref("MessageEvent.source")}} {{ReadOnlyInline}} - : A `MessageEventSource` (which can be a {{glossary("WindowProxy")}}, {{domxref("MessagePort")}}, or {{domxref("ServiceWorker")}} object) representing the message emitter. - {{domxref("MessageEvent.ports")}} {{ReadOnlyInline}} - : An array of {{domxref("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>`](/en-US/docs/Web/HTML/Element/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()`](/en-US/docs/Web/API/EventTarget/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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Related events: [`messageerror`](/en-US/docs/Web/API/Window/messageerror_event). - [`Window.postMessage()`](/en-US/docs/Web/API/Window/postMessage).
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/innerwidth/index.md
--- title: "Window: innerWidth property" short-title: innerWidth slug: Web/API/Window/innerWidth page-type: web-api-instance-property browser-compat: api.Window.innerWidth --- {{APIRef}} The read-only {{domxref("Window")}} property **`innerWidth`** returns the interior width of the window in pixels (that is, the width of the window's {{Glossary("layout viewport")}}). That includes the width of the vertical scroll bar, if one is present. Similarly, the interior height of the window (that is, the height of the layout viewport) can be obtained using the {{domxref("Window.innerHeight", "innerHeight")}} property. That measurement also accounts for the height of the horizontal scroll bar, if it is visible. ## Value An integer value indicating the width of the window's layout viewport in pixels. This property is read-only, and has no default value. To change the window's width, use one of the {{domxref("Window")}} methods for resizing windows, such as {{domxref("Window.resizeBy", "resizeBy()")}} or {{domxref("Window.resizeTo", "resizeTo()")}}. ## Usage notes If you need to obtain the width of the window minus the scrollbar and borders, use the root {{HTMLElement("html")}} element's {{domxref("Element.clientWidth", "clientWidth")}} property instead. The `innerWidth` property is available on any window or object that behaves like a window, such as a frame or tab. ## Examples ```js // This will log the width of the viewport console.log(window.innerWidth); // This will log the width of the frame viewport within a frameset console.log(self.innerWidth); // This will log the width of the viewport of the closest frameset console.log(parent.innerWidth); // This will log the width of the viewport of the outermost frameset console.log(top.innerWidth); ``` ## Demo ### HTML ```html <p>Resize the browser window to fire the <code>resize</code> event.</p> <p>Window height: <span id="height"></span></p> <p>Window width: <span id="width"></span></p> ``` ### JavaScript ```js const heightOutput = document.querySelector("#height"); const widthOutput = document.querySelector("#width"); function updateSize() { heightOutput.textContent = window.innerHeight; widthOutput.textContent = window.innerWidth; } updateSize(); window.addEventListener("resize", updateSize); ``` ### Result {{EmbedLiveSample('Demo')}} You can also {{LiveSampleLink('Demo', 'view the results of the demo code in a separate page')}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.outerWidth")}} - {{domxref("window.innerHeight")}} - {{domxref("window.outerHeight")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/load_event/index.md
--- title: "Window: load event" short-title: load slug: Web/API/Window/load_event page-type: web-api-event browser-compat: api.Window.load_event --- {{APIRef}} The **`load`** event is fired when the whole page has loaded, including all dependent resources such as stylesheets, scripts, iframes, and images. This is in contrast to {{domxref("Document/DOMContentLoaded_event", "DOMContentLoaded")}}, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading. This event is not cancelable and does not bubble. > **Note:** _All events named `load` will not propagate to `Window`_, even with `bubbles` initialized to `true`. To catch `load` events on the `window`, that `load` event must be dispatched directly to the `window`. > **Note:** The `load` event that is dispatched when the main document has loaded _is_ dispatched on the `window`, but has two mutated properties: `target` is `document`, and `path` is `undefined`. These two properties are mutated due to legacy conformance. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("load", (event) => {}); onload = (event) => {}; ``` ## Event type A generic {{domxref("Event")}}. ## Examples Log a message when the page is fully loaded: ```js window.addEventListener("load", (event) => { console.log("page is fully loaded"); }); ``` The same, but using the `onload` event handler property: ```js window.onload = (event) => { console.log("page is fully loaded"); }; ``` ### Live example #### HTML ```html <div class="controls"> <button id="reload" type="button">Reload</button> </div> <div class="event-log"> <label for="eventLog">Event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="30" id="eventLog"></textarea> </div> ``` ```css hidden body { display: grid; grid-template-areas: "control log"; } .controls { grid-area: control; display: flex; align-items: center; justify-content: center; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } #reload { height: 2rem; } ``` #### JavaScript ```js const log = document.querySelector(".event-log-contents"); const reload = document.querySelector("#reload"); reload.addEventListener("click", () => { log.textContent = ""; setTimeout(() => { window.location.reload(true); }, 200); }); window.addEventListener("load", (event) => { log.textContent += "load\n"; }); document.addEventListener("readystatechange", (event) => { log.textContent += `readystate: ${document.readyState}\n`; }); document.addEventListener("DOMContentLoaded", (event) => { log.textContent += `DOMContentLoaded\n`; }); ``` #### Result {{ EmbedLiveSample('Live_example', '100%', '160px') }} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - Document [readyState](/en-US/docs/Web/API/Document/readyState) API - Related events: - {{domxref("Document/DOMContentLoaded_event", "DOMContentLoaded")}} - {{domxref("Document/readystatechange_event", "readystatechange")}} - {{domxref("Window/beforeunload_event", "beforeunload")}} - {{domxref("Window/unload_event", "unload")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/getdefaultcomputedstyle/index.md
--- title: "Window: getDefaultComputedStyle() method" short-title: getDefaultComputedStyle() slug: Web/API/window/getDefaultComputedStyle page-type: web-api-instance-method status: - non-standard browser-compat: api.Window.getDefaultComputedStyle --- {{APIRef("CSSOM")}}{{Non-standard_Header}} The **`getDefaultComputedStyle()`** method gives the default [computed values](/en-US/docs/Web/CSS/computed_value) of all the CSS properties of an element, ignoring author styling. That is, only user-agent and user styles are taken into account. ## Syntax ```js-nolint getDefaultComputedStyle(element) getDefaultComputedStyle(element, pseudoElt) ``` ### Parameters - `element` - : The {{domxref("Element")}} for which to get the computed style. - `pseudoElt` {{optional_inline}} - : A string specifying the pseudo-element to match. Must be `null` (or not specified) for regular elements. ### Return value The returned `style` is a [`CSSStyleDeclaration`](/en-US/docs/Web/API/CSSStyleDeclaration) object. The object is of the same type as the object returned by {{domxref("Window.getComputedStyle()")}}, but only takes into account user-agent and user rules. ## Examples ### Simple example ```js const elem1 = document.getElementById("elemId"); const style = window.getDefaultComputedStyle(elem1); ``` ### Longer example ```html <style> #elem-container { position: absolute; left: 100px; top: 200px; height: 100px; } </style> <div id="elem-container">dummy</div> <div id="output"></div> <script> const elem = document.getElementById("elem-container"); const theCSSprop = window.getDefaultComputedStyle(elem).position; document.getElementById("output").innerHTML = theCSSprop; // Will output "static" </script> ``` ### Use with pseudo-elements The `getDefaultComputedStyle()` method can pull style info from pseudo-elements (e.g., {{cssxref("::before")}} or {{cssxref("::after")}}). ```html <style> h3:after { content: " rocks!"; } </style> <h3>generated content</h3> <script> const h3 = document.querySelector("h3"); const result = getDefaultComputedStyle(h3, ":after").content; console.log("the generated content is: ", result); // returns 'none' </script> ``` ## Notes The returned value is, in certain known cases, expressly incorrect by deliberate intent. In particular, to avoid the so called CSS History Leak security issue, browsers may expressly "lie" about the used value for a link and always return values as if a user has never visited the linked site, and/or limit the styles that can be applied using the `:visited` pseudo-selector. See <https://blog.mozilla.com/security/2010/03/31/plugging-the-css-history-leak/> and <https://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/> for details of the examples of how this is implemented. ## Specifications Proposed to the CSS working group. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/menubar/index.md
--- title: "Window: menubar property" short-title: menubar slug: Web/API/Window/menubar page-type: web-api-instance-property browser-compat: api.Window.menubar --- {{ APIRef() }} Returns the `menubar` object. This is one of a group of `Window` properties that contain a boolean `visible` property, that used to represent whether or not a particular part of a web browser's user interface was visible. For privacy and interoperability reasons, the value of the `visible` property is now `false` if this `Window` is a popup, and `true` otherwise. ## Value An object containing a single property: - `visible` {{ReadOnlyInline}} - : A boolean property, `false` if this `Window` is a popup, and `true` otherwise. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("window.locationbar")}} - {{domxref("window.personalbar")}} - {{domxref("window.scrollbars")}} - {{domxref("window.statusbar")}} - {{domxref("window.toolbar")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/rejectionhandled_event/index.md
--- title: "Window: rejectionhandled event" short-title: rejectionhandled slug: Web/API/Window/rejectionhandled_event page-type: web-api-event browser-compat: api.Window.rejectionhandled_event --- {{APIRef("HTML DOM")}} The **`rejectionhandled`** event is sent to the script's global scope (usually {{domxref("window")}} but also {{domxref("Worker")}}) whenever a rejected JavaScript {{jsxref("Promise")}} is handled late, i.e. when a handler is attached to the promise after its rejection had caused an {{domxref("Window.unhandledrejection_event", "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 {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("rejectionhandled", (event) => {}); onrejectionhandled = (event) => {}; ``` ## Event type A {{domxref("PromiseRejectionEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("PromiseRejectionEvent")}} ## Event properties - {{domxref("PromiseRejectionEvent.promise")}} {{ReadOnlyInline}} - : The JavaScript {{jsxref("Promise")}} that was rejected. - {{domxref("PromiseRejectionEvent.reason")}} {{ReadOnlyInline}} - : A value or {{jsxref("Object")}} indicating why the promise was rejected, as passed to {{jsxref("Promise.reject()")}}. ## Event handler aliases In addition to the `Window` interface, the event handler property `onrejectionhandled` is also available on the following targets: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("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 {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Promise rejection events](/en-US/docs/Web/JavaScript/Guide/Using_promises#promise_rejection_events) - {{domxref("PromiseRejectionEvent")}} - {{jsxref("Promise")}} - {{domxref("Window/unhandledrejection_event", "unhandledrejection")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/blur/index.md
--- title: "Window: blur() method" short-title: blur() slug: Web/API/Window/blur page-type: web-api-instance-method status: - deprecated browser-compat: api.Window.blur --- {{APIRef}} The **`Window.blur()`** method does nothing. > **Note:** Historically, this method was the programmatic equivalent of the user shifting focus away > from the current window. This behavior was removed due to hostile sites abusing this functionality. > In Firefox, you can enable the old behavior with the `dom.disable_window_flip` preference. ## Syntax ```js-nolint blur() ``` ### Parameters None. ### Return value None ({{jsxref("undefined")}}). ## Examples ```js window.blur(); ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/devicepixelratio/index.md
--- title: "Window: devicePixelRatio property" short-title: devicePixelRatio slug: Web/API/Window/devicePixelRatio page-type: web-api-instance-property browser-compat: api.Window.devicePixelRatio --- {{APIRef}} The **`devicePixelRatio`** of {{domxref("Window")}} interface returns the ratio of the resolution in _physical pixels_ to the resolution in _CSS pixels_ for the current display device. This value could also be interpreted as the ratio of pixel sizes: the size of one _CSS pixel_ to the size of one _physical pixel_. In simpler terms, this tells the browser how many of the screen's actual pixels should be used to draw a single CSS pixel. This is useful when dealing with the difference between rendering on a standard display versus a HiDPI or Retina display, which use more screen pixels to draw the same objects, resulting in a sharper image. You can use {{domxref("Window.matchMedia", "window.matchMedia()")}} to check if the value of `devicePixelRatio` changes (which can happen, for example, if the user drags the window to a display with a different pixel density). See [the example below](#monitoring_screen_resolution_or_zoom_level_changes). ## Value A double-precision floating-point value indicating the ratio of the display's resolution in physical pixels to the resolution in CSS pixels. A value of 1 indicates a classic 96 DPI display, while a value of 2 is expected for HiDPI/Retina displays. Other values may be returned in the case of unusually low resolution displays or, more often, when a screen has a higher pixel density than double the standard resolution of 96 DPI. Modern mobile device screens - which offer high display resolutions at small physical sizes - often yield a `devicePixelRatio` value greater than 2. ## Examples ### Correcting resolution in a `<canvas>` A {{htmlelement("canvas")}} can appear too blurry on retina screens. Use `window.devicePixelRatio` to determine how much extra pixel density should be added to allow for a sharper image. #### HTML ```html <canvas id="canvas"></canvas> ``` #### JavaScript ```js const canvas = document.getElementById("canvas"); const ctx = canvas.getContext("2d"); // Set display size (css pixels). const size = 200; canvas.style.width = `${size}px`; canvas.style.height = `${size}px`; // Set actual size in memory (scaled to account for extra pixel density). const scale = window.devicePixelRatio; // Change to 1 on retina screens to see blurry canvas. canvas.width = Math.floor(size * scale); canvas.height = Math.floor(size * scale); // Normalize coordinate system to use CSS pixels. ctx.scale(scale, scale); ctx.fillStyle = "#bada55"; ctx.fillRect(10, 10, 300, 300); ctx.fillStyle = "#ffffff"; ctx.font = "18px Arial"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; const x = size / 2; const y = size / 2; const textString = "I love MDN"; ctx.fillText(textString, x, y); ``` [![Side-by-side comparison of the effect of different devicePixelRatio values on an image shown in a retina display.](devicepixelratio_diff.png)](devicepixelratio_diff.png) ### Monitoring screen resolution or zoom level changes In this example, we'll set up a media query and watch it to see when the device resolution changes, logging the new resolution. #### HTML ```html <div id="container"> <p> This example demonstrates the effect of zooming the page in and out (or moving it to a screen with a different scaling factor) on the value of the <code>devicePixelRatio</code> property.</p> <p>Try it and watch what happens!</p> </p> </div> <div id="output"></div> ``` #### CSS ```css body { font: 22px arial, sans-serif; } #container { border: 2px solid #22d; margin: 1rem auto; padding: 1rem; background-color: #a9f; } ``` #### JavaScript The string `mqString` is set to a media query which checks to see if the current display resolution matches a specific number of device dots per `px`. The `media` variable is a {{domxref("MediaQueryList")}} object that's initialized with the media query string. When the result of running `mqString` against the document changes, the `media` object's `change` event fires, and the code logs the new resolution. Note that every time the resolution changes, the example has to create a new media query, based on the new resolution, and a new `MediaQueryList` instance. ```js let remove = null; const output = document.querySelector("#output"); const updatePixelRatio = () => { if (remove != null) { remove(); } const mqString = `(resolution: ${window.devicePixelRatio}dppx)`; const media = matchMedia(mqString); media.addEventListener("change", updatePixelRatio); remove = () => { media.removeEventListener("change", updatePixelRatio); }; output.textContent = `devicePixelRatio: ${window.devicePixelRatio}`; }; updatePixelRatio(); ``` #### Result To test the example, try zooming the page in and out, and note the difference in the logged value of `devicePixelRatio`. {{EmbedLiveSample("Monitoring_screen_resolution_or_zoom_level_changes", "100%", 300)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - [Media queries](/en-US/docs/Web/CSS/CSS_media_queries) - [Using media queries](/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries) - [CSS `resolution` media query](/en-US/docs/Web/CSS/@media/resolution) - The {{cssxref("image-resolution")}} property
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/launchqueue/index.md
--- title: "Window: launchQueue property" short-title: launchQueue slug: Web/API/Window/launchQueue page-type: web-api-instance-property status: - experimental browser-compat: api.Window.launchQueue --- {{APIRef("Launch Handler API")}}{{SeeCompatTable}} The `launchQueue` read-only property of the {{domxref("Window")}} interface provides access to the {{domxref("LaunchQueue")}} class, which allows custom launch navigation handling to be implemented in a [progressive web app](/en-US/docs/Web/Progressive_web_apps) (PWA), with the handling context signified by the [`launch_handler`](/en-US/docs/Web/Manifest/launch_handler) manifest field `client_mode` value. The custom launch navigation handling functionality is controlled by the properties of the {{domxref("LaunchParams")}} object passed into the {{domxref("LaunchQueue.setConsumer()")}} callback function. ## Value A {{domxref("LaunchQueue")}} object instance. ## Examples ```js if ("launchQueue" in window) { window.launchQueue.setConsumer((launchParams) => { if (launchParams.targetURL) { const params = new URL(launchParams.targetURL).searchParams; // Assuming a music player app that gets a track passed to it to be played const track = params.get("track"); if (track) { audio.src = track; title.textContent = new URL(track).pathname.substring(1); audio.play(); } } }); } ``` ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Launch Handler API", "Launch Handler API", "", "nocode")}} - [Launch Handler API: Control how your app is launched](https://developer.chrome.com/docs/web-platform/launch-handler/) - {{domxref("Window.launchQueue")}} - [Musicr 2.0](https://launch-handler.glitch.me/) demo app
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/console/index.md
--- title: "Window: console property" short-title: console slug: Web/API/Window/console page-type: web-api-instance-property spec-urls: https://console.spec.whatwg.org/ --- {{APIRef}} The **`Window.console`** property returns a reference to the {{domxref("console")}} object, which provides methods for logging information to the browser's console. These methods are intended for debugging purposes only and should not be relied on for presenting information to end users. ## Examples ### Logging to console The first example logs text to the console. ```js console.log("An error occurred while loading the content"); ``` The next example logs an object to the console, with the object's fields expandable using disclosure widgets: ```js console.dir(someObject); ``` For more examples, see the [Examples](/en-US/docs/Web/API/console#examples) section of the [`console`](/en-US/docs/Web/API/console) article. ## Specifications {{Specifications}} > **Note:** Currently there are many implementation differences among browsers, but work is being done to bring them together and make them more consistent with one another.
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/beforeinstallprompt_event/index.md
--- title: "Window: beforeinstallprompt event" short-title: beforeinstallprompt slug: Web/API/Window/beforeinstallprompt_event page-type: web-api-event browser-compat: api.Window.beforeinstallprompt_event --- {{APIRef}} The **`beforeinstallprompt`** event fires when the browser has detected that a website can be [installed as a Progressive Web App](/en-US/docs/Web/Progressive_web_apps/Guides/Making_PWAs_installable). There's no guaranteed time this event is fired, but it usually happens on page load. The typical use for this event is when a web app wants to provide its own in-app UI inviting the user to install the app, rather than the generic one provided by the browser. This enables the app to provide more context about the app, explaining to the user why they might want to install it. In this scenario, the handler for this event will: - Keep a reference to the {{domxref("BeforeInstallPromptEvent")}} object that's passed into it - Reveal its in-app installation UI (this should be hidden by default, because not all browsers will support installation). When the user uses the in-app installation UI to install the app, the in-app installation UI calls the {{domxref("BeforeInstallPromptEvent.prompt()", "prompt()")}} method of the retained `BeforeInstallPromptEvent` object to show the installation prompt. ## Syntax Use the event name in methods like {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("beforeinstallprompt", (event) => {}); onbeforeinstallprompt = (event) => {}; ``` ## Event type A {{domxref("BeforeInstallPromptEvent")}}. Inherits from {{domxref("Event")}}. {{InheritanceDiagram("BeforeInstallPromptEvent")}} ## Event properties _Inherits properties from its parent, {{domxref("Event")}}._ - {{domxref("BeforeInstallPromptEvent.platforms")}} {{ReadOnlyInline}}{{Non-standard_Inline}} {{Experimental_Inline}} - : Returns an array of string items containing the platforms on which the event was dispatched. This is provided for user agents that want to present a choice of versions to the user such as, for example, "web" or "play" which would allow the user to choose between a web version or an Android version. - {{domxref("BeforeInstallPromptEvent.userChoice")}} {{ReadOnlyInline}}{{Non-standard_Inline}} {{Experimental_Inline}} - : Returns a {{jsxref("Promise")}} that resolves to an object describing the user's choice when they were prompted to install the app. ## Event methods - {{domxref("BeforeInstallPromptEvent.prompt()")}}{{Non-standard_Inline}} {{Experimental_Inline}} - : Show a prompt asking the user if they want to install the app. This method returns a {{jsxref("Promise")}} that resolves to an object describing the user's choice when they were prompted to install the app. ## Examples In the following example an app provides its own install button, which has an `id` of `"install"`. Initially the button is hidden. ```html <button id="install" hidden>Install</button> ``` The `beforeinstallprompt` handler: - Cancels the event, which prevents the browser displaying its own install UI on some platforms - Assigns the `BeforeInstallPromptEvent` object to a variable, so it can be used later - Reveals the app's install button. ```js let installPrompt = null; const installButton = document.querySelector("#install"); window.addEventListener("beforeinstallprompt", (event) => { event.preventDefault(); installPrompt = event; installButton.removeAttribute("hidden"); }); ``` When clicked, the app's install button: - Calls the {{domxref("BeforeInstallPromptEvent.prompt()", "prompt()")}} method of the stored event object, to trigger the installation prompt. - Resets its state by clearing the `installPrompt` variable and hiding itself again. ```js installButton.addEventListener("click", async () => { if (!installPrompt) { return; } const result = await installPrompt.prompt(); console.log(`Install prompt was: ${result.outcome}`); installPrompt = null; installButton.setAttribute("hidden", ""); }); ``` ## Browser compatibility {{Compat}} ## See also - {{domxref("BeforeInstallPromptEvent.prompt")}} - {{domxref("BeforeInstallPromptEvent")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/event/index.md
--- title: "Window: event property" short-title: event slug: Web/API/Window/event page-type: web-api-instance-property status: - deprecated browser-compat: api.Window.event --- {{APIRef("DOM")}}{{Deprecated_Header}} The read-only {{domxref("Window")}} property **`event`** returns the {{domxref("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 {{domxref("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 {{Glossary("shadow tree", "shadow trees")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("Event.srcElement")}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/updatecommands/index.md
--- title: "Window: updateCommands() method" short-title: updateCommands() slug: Web/API/Window/updateCommands page-type: web-api-instance-method status: - non-standard browser-compat: api.Window.updateCommands --- {{ApiRef}}{{Non-standard_Header}} Updates the state of commands of the current chrome window (UI). ## Syntax ```js-nolint updateCommands("sCommandName") ``` ### Parameters - `sCommandName` is a particular string which describes what kind of update event this is (e.g. whether we are in bold right now). ### Return value None ({{jsxref("undefined")}}). ## Notes This enables or disables items (setting or clearing the "disabled" attribute on the command node as appropriate), or ensures that the command state reflects the state of the selection by setting current state information in the "state" attribute of the XUL command nodes. ## Specifications DOM Level 0. Not part of specification. ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/scrollto/index.md
--- title: "Window: scrollTo() method" short-title: scrollTo() slug: Web/API/Window/scrollTo page-type: web-api-instance-method browser-compat: api.Window.scrollTo --- {{APIRef}} **`Window.scrollTo()`** scrolls to a particular set of coordinates in the document. ## Syntax ```js-nolint scrollTo(x-coord, y-coord) scrollTo(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 {{cssxref("scroll-behavior")}} ### Return value None ({{jsxref("undefined")}}). ## Examples ```js window.scrollTo(0, 1000); ``` Using `options`: ```js window.scrollTo({ top: 100, left: 100, behavior: "smooth", }); ``` ## Notes {{domxref("Window.scroll()")}} is effectively the same as this method. For relative scrolling, see {{domxref("Window.scrollBy()")}}, {{domxref("Window.scrollByLines()")}}, and {{domxref("Window.scrollByPages()")}}. For scrolling elements, see {{domxref("Element.scrollTop")}} and {{domxref("Element.scrollLeft")}}. ## Specifications {{Specifications}} ## Browser compatibility {{Compat}}
0
data/mdn-content/files/en-us/web/api/window
data/mdn-content/files/en-us/web/api/window/beforeunload_event/index.md
--- title: "Window: beforeunload event" short-title: beforeunload slug: Web/API/Window/beforeunload_event page-type: web-api-event browser-compat: api.Window.beforeunload_event --- {{APIRef}} 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 {{domxref("Event.preventDefault()", "preventDefault()")}} method. - Setting the event object's {{domxref("BeforeUnloadEvent.returnValue", "returnValue")}} property to a non-empty string value or any other [truthy](/en-US/docs/Glossary/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 {{domxref("EventTarget.addEventListener", "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 {{domxref("EventTarget.addEventListener", "addEventListener()")}}, or set an event handler property. ```js addEventListener("beforeunload", (event) => {}); onbeforeunload = (event) => {}; ``` ## Event type A {{domxref("BeforeUnloadEvent")}}. Inherits from {{domxref("Event")}}. ## Usage notes To trigger the dialog being shown when the user closes or navigates the tab, a `beforeunload` event handler function should call {{domxref("Event.preventDefault()", "preventDefault()")}} on the event object. You should note that modern implementations: - Require [sticky activation](/en-US/docs/Glossary/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 {{domxref("Document.visibilitychange_event", "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](https://www.igvita.com/2015/11/20/dont-lose-user-and-app-state-use-page-visibility/) for more details. - In Firefox, `beforeunload` is not compatible with the [back/forward cache](https://web.dev/articles/bfcache) (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: - {{domxref("HTMLBodyElement")}} - {{domxref("HTMLFrameSetElement")}} - {{domxref("SVGSVGElement")}} ## Examples In the following example we have an HTML text {{htmlelement("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 {{domxref("Element/input_event", "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 {{domxref("Window.beforeunload_event", "beforeunload")}} event listener is attached to the {{domxref("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](#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: {{EmbedLiveSample("Examples", "100%", 50)}} ## Specifications {{Specifications}} ## Browser compatibility {{Compat}} ## See also - {{domxref("BeforeUnloadEvent")}} interface - Related events: - {{domxref("Document/DOMContentLoaded_event", "DOMContentLoaded")}} - {{domxref("Document/readystatechange_event", "readystatechange")}} - {{domxref("Window/load_event", "load")}} - {{domxref("Window/unload_event", "unload")}} - [Page Lifecycle API](https://developer.chrome.com/blog/page-lifecycle-api/#developer-recommendations-for-each-state) provides more useful guidance on handling page lifecycle behavior in your web apps.
0