Window
Baseline Widely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
TheWindow interface represents a window containing aDOM document; thedocument property points to theDOM document loaded in that window.
A window for a given document can be obtained using thedocument.defaultView property.
A global variable,window, representing the window in which the script is running, is exposed to JavaScript code.
TheWindow interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window. However, theWindow interface is a suitable place to include these items that need to be globally available. Many of these are documented in theJavaScript Reference and theDOM Reference.
In a tabbed browser, each tab is represented by its ownWindow object; the globalwindow seen by JavaScript code running within a given tab always represents the tab in which the code is running. That said, even in a tabbed browser, some properties and methods still apply to the overall window that contains the tab, such asresizeTo() andinnerHeight. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.
In this article
Instance properties
This interface inherits properties from theEventTarget interface.
Note that properties which are objects (e.g., for overriding the prototype of built-in elements) are listed in a separate section below.
Window.cachesRead onlySecure contextReturns the
CacheStorageobject associated with the current context. This object enables functionality such as storing assets for offline use, and generating custom responses to requests.Window.clientInformationRead onlyAn alias for
Window.navigator.Window.closedRead onlyThis property indicates whether the current window is closed or not.
Window.cookieStoreRead onlySecure contextReturns a reference to the
CookieStoreobject for the current document context.Window.credentiallessRead onlyExperimentalReturns a boolean that indicates whether the current document was loaded inside a credentialless
<iframe>. SeeIFrame credentialless for more details.Window.crossOriginIsolatedRead onlyReturns a boolean value that indicates whether the website is in a cross-origin isolation state.
Window.cryptoRead onlyReturns the
Cryptoobject associated to the global object.Window.customElementsRead onlyReturns a reference to the
CustomElementRegistryobject, which can be used to register newcustom elements and get information about previously registered custom elements.Window.devicePixelRatioRead onlyReturns the ratio between physical pixels and device independent pixels in the current display.
Window.documentRead onlyReturns a reference to the document that the window contains.
Window.documentPictureInPictureRead onlyExperimentalSecure contextReturns a reference to thedocument Picture-in-Picture window for the current document context.
Window.fenceRead onlyExperimentalReturns a
Fenceobject instance for the current document context. Available only to documents embedded inside a<fencedframe>.Window.frameElementRead onlyReturns the element in which the window is embedded, or null if the window is not embedded.
Window.framesRead onlyReturns an array of the subframes in the current window.
Window.fullScreenNon-standardThis property indicates whether the window is displayed in full screen or not.
Window.historyRead onlyReturns a reference to the history object.
Window.indexedDBRead onlyProvides a mechanism for applications to asynchronously access capabilities of indexed databases; returns an
IDBFactoryobject.Window.innerHeightRead onlyGets the height of the content area of the browser window including, if rendered, the horizontal scrollbar.
Window.innerWidthRead onlyGets the width of the content area of the browser window including, if rendered, the vertical scrollbar.
Window.isSecureContextRead onlyReturns a boolean indicating whether the current context is secure (
true) or not (false).Window.launchQueueRead onlyExperimentalWhen aprogressive web app (PWA) is launched with a
launch_handlerclient_modevalue offocus-existing,navigate-new, ornavigate-existing, thelaunchQueueprovides access to theLaunchQueueclass, which allows custom launch navigation handling to be implemented for the PWA.Window.lengthRead onlyReturns the number of frames in the window. See also
window.frames.Window.localStorageRead onlyReturns a reference to the local storage object used to store data that may only be accessed by the origin that created it.
Window.locationGets/sets the location, or current URL, of the window object.
Window.locationbarRead onlyReturns the locationbar object.
Window.menubarRead onlyReturns the menubar object.
Window.mozInnerScreenXRead onlyNon-standardReturns the horizontal (X) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See
mozScreenPixelsPerCSSPixelinnsIDOMWindowUtilsfor a conversion factor to adapt to screen pixels if needed.Window.mozInnerScreenYRead onlyNon-standardReturns the vertical (Y) coordinate of the top-left corner of the window's viewport, in screen coordinates. This value is reported in CSS pixels. See
mozScreenPixelsPerCSSPixelfor a conversion factor to adapt to screen pixels if needed.Window.nameGets/sets the name of the window.
Window.navigationRead onlyExperimentalReturns the current
window's associatedNavigationobject. The entry point for theNavigation API.Window.navigatorRead onlyReturns a reference to the navigator object.
Window.openerReturns a reference to the window that opened this current window.
Window.originRead onlyReturns the global object's origin, serialized as a string.
Window.originAgentClusterRead onlyReturns
trueif this window belongs to an origin-keyed agent cluster.Window.outerHeightRead onlyGets the height of the outside of the browser window.
Window.outerWidthRead onlyGets the width of the outside of the browser window.
Window.pageXOffsetRead onlyAn alias for
window.scrollX.Window.pageYOffsetRead onlyAn alias for
window.scrollY.Window.parentRead onlyReturns a reference to the parent of the current window or subframe.
Window.performanceRead onlyReturns a
Performanceobject, which includes thetimingandnavigationattributes, each of which is an object providingperformance-related data. See alsoUsing Navigation Timing for additional information and examples.Window.personalbarRead onlyReturns the personalbar object.
Window.schedulerRead onlyReturns the
Schedulerobject associated with the current context. This is the entry point for using thePrioritized Task Scheduling API.Window.screenRead onlyReturns a reference to the screen object associated with the window.
Window.screenXandWindow.screenLeftRead onlyBoth properties return the horizontal distance from the left border of the user's browser viewport to the left side of the screen.
Window.screenYandWindow.screenTopRead onlyBoth properties return the vertical distance from the top border of the user's browser viewport to the top side of the screen.
Window.scrollbarsRead onlyReturns the scrollbars object.
Window.scrollMaxXNon-standardRead onlyThe maximum offset that the window can be scrolled to horizontally, that is the document width minus the viewport width.
Window.scrollMaxYNon-standardRead onlyThe maximum offset that the window can be scrolled to vertically (i.e., the document height minus the viewport height).
Window.scrollXRead onlyReturns the number of pixels that the document has already been scrolled horizontally.
Window.scrollYRead onlyReturns the number of pixels that the document has already been scrolled vertically.
Window.selfRead onlyReturns an object reference to the window object itself.
Window.sessionStorageReturns a reference to the session storage object used to store data that may only be accessed by the origin that created it.
Window.sharedStorageRead onlyExperimentalSecure contextReturns the
WindowSharedStorageobject for the current origin. This is the main entry point for writing data to shared storage using theShared Storage API.Window.speechSynthesisRead onlyReturns a
SpeechSynthesisobject, which is the entry point into usingWeb Speech API speech synthesis functionality.Window.statusbarRead onlyReturns the statusbar object.
Window.toolbarRead onlyReturns the toolbar object.
Window.topRead onlyReturns a reference to the topmost window in the window hierarchy. This property is read only.
Window.trustedTypesRead onlyReturns the
TrustedTypePolicyFactoryobject associated with the global object, providing the entry point for using theTrusted Types API.Window.viewportExperimentalRead onlyReturns a
Viewportobject instance, which provides information about the current state of the device's viewport.Window.visualViewportRead onlyReturns a
VisualViewportobject which represents the visual viewport for a given window.Window.windowRead onlyReturns a reference to the current window.
window[0],window[1], etc.Returns a reference to the
windowobject in the frames. SeeWindow.framesfor more details.- Named properties
Some elements in the document are also exposed as window properties:
- For each
<embed>,<form>,<iframe>,<img>, and<object>element, itsname(if non-empty) is exposed.For example, if the document contains<form name="my_form">, thenwindow["my_form"](and its equivalentwindow.my_form) returns a reference to that element. - For each HTML element, its
id(if non-empty) is exposed.
If a property corresponds to a single element, that element is directly returned. If the property corresponds to multiple elements, then an
HTMLCollectionis returned containing all of them. If any of the elements is a navigable<iframe>or<object>, then thecontentWindowof first such iframe is returned instead.- For each
Deprecated properties
Window.eventDeprecatedRead onlyReturns thecurrent event, which is the event currently being handled by the JavaScript code's context, or
undefinedif no event is currently being handled. TheEventobject passed directly to event handlers should be used instead whenever possible.Window.externalDeprecatedRead onlyReturns an object with functions for adding external search providers to the browser.
Window.orientationDeprecatedRead onlyReturns the orientation in degrees (in 90 degree increments) of the viewport relative to the device's natural orientation.
Window.statusDeprecatedGets/sets the text in the statusbar at the bottom of the browser.
Instance methods
This interface inherits methods from theEventTarget interface.
Window.atob()Decodes a string of data which has been encoded using base-64 encoding.
Window.alert()Displays an alert dialog.
Window.blur()DeprecatedSets focus away from the window.
Window.btoa()Creates a base-64 encoded ASCII string from a string of binary data.
Window.cancelAnimationFrame()Enables you to cancel a callback previously scheduled with
Window.requestAnimationFrame.Window.cancelIdleCallback()Enables you to cancel a callback previously scheduled with
Window.requestIdleCallback.Window.clearInterval()Cancels the repeated execution set using
Window.setInterval().Window.clearTimeout()Cancels the delayed execution set using
Window.setTimeout().Window.close()Closes the current window.
Window.confirm()Displays a dialog with a message that the user needs to respond to.
Window.createImageBitmap()Accepts a variety of different image sources, and returns a
Promisewhich resolves to anImageBitmap. Optionally the source is cropped to the rectangle of pixels originating at(sx, sy) with width sw, and height sh.Window.dump()Non-standardWrites a message to the console.
Window.fetch()Starts the process of fetching a resource from the network.
Window.fetchLater()ExperimentalCreates a deferred fetch, which is sent once the page is navigated away from (it is destroyed or enters thebfcache), or after a provided
activateAftertimeout — whichever comes first.Window.find()Non-standardSearches for a given string in a window.
Window.focus()Sets focus on the current window.
Window.getComputedStyle()Gets computed style for the specified element. Computed style indicates the computed values of all CSS properties of the element.
Window.getDefaultComputedStyle()Non-standardGets default computed style for the specified element, ignoring author stylesheets.
Window.getScreenDetails()ExperimentalSecure contextReturns a
Promisethat fulfills with aScreenDetailsobject instance representing the details of all the screens available to the user's device.Window.getSelection()Returns the selection object representing the selected item(s).
Window.matchMedia()Returns a
MediaQueryListobject representing the specified media query string.Window.moveBy()Moves the current window by a specified amount.
Window.moveTo()Moves the window to the specified coordinates.
Window.open()Opens a new window.
Window.postMessage()Provides a secure means for one window to send a string of data to another window, which need not be within the same domain as the first.
Window.print()Opens the Print Dialog to print the current document.
Window.prompt()Returns the text entered by the user in a prompt dialog.
Window.queryLocalFonts()ExperimentalSecure contextReturns a
Promisethat fulfills with an array ofFontDataobjects representing the font faces available locally.Window.queueMicrotask()Queues a microtask to be executed at a safe time prior to control returning to the browser's event loop.
Window.reportError()Reports an error in a script, emulating an unhandled exception.
Window.requestAnimationFrame()Tells the browser that an animation is in progress, requesting that the browser schedule a repaint of the window for the next animation frame.
Window.requestIdleCallback()Enables the scheduling of tasks during a browser's idle periods.
Window.resizeBy()Resizes the current window by a certain amount.
Window.resizeTo()Dynamically resizes window.
Window.scroll()Scrolls the window to a particular place in the document.
Window.scrollBy()Scrolls the document in the window by the given amount.
Window.scrollByLines()Non-standardScrolls the document by the given number of lines.
Window.scrollByPages()Non-standardScrolls the current document by the specified number of pages.
Window.scrollTo()Scrolls to a particular set of coordinates in the document.
Window.setInterval()Schedules a function to execute every time a given number of milliseconds elapses.
Window.setTimeout()Schedules a function to execute in a given amount of time.
Window.showDirectoryPicker()ExperimentalSecure contextDisplays a directory picker which allows the user to select a directory.
Window.showOpenFilePicker()ExperimentalSecure contextShows a file picker that allows a user to select a file or multiple files.
Window.showSaveFilePicker()ExperimentalSecure contextShows a file picker that allows a user to save a file.
Window.sizeToContent()Non-standardSizes the window according to its content.
Window.stop()This method stops window loading.
Window.structuredClone()Creates adeep clone of a given value using thestructured clone algorithm.
Deprecated methods
Window.captureEvents()DeprecatedRegisters the window to capture all events of the specified type.
Window.clearImmediate()Non-standardDeprecatedCancels the repeated execution set using
setImmediate().Window.releaseEvents()DeprecatedReleases the window from trapping events of a specific type.
Window.requestFileSystem()Non-standardDeprecatedLets a website or app gain access to a sandboxed file system for its own use.
Window.setImmediate()Non-standardDeprecatedExecutes a function after the browser has finished other heavy tasks.
Window.setResizable()Non-standardDeprecatedDoes nothing (no-op). Kept for backward compatibility with Netscape 4.x.
Window.webkitConvertPointFromNodeToPage()Non-standardDeprecatedTransforms a
WebKitPointfrom the node's coordinate system to the page's coordinate system.Window.webkitConvertPointFromPageToNode()Non-standardDeprecatedTransforms a
WebKitPointfrom the page's coordinate system to the node's coordinate system.
Events
Listen to these events usingaddEventListener() or by assigning an event listener to theoneventname property of this interface. In addition to the events listed below, many events can bubble from theDocument contained in the window object.
errorFired when a resource failed to load, or can't be used. For example, if a script has an execution error or an image can't be found or is invalid.
languagechangeFired at the global scope object when the user's preferred language changes.
resizeFired when the window has been resized.
storageFired when a storage area (
localStorageorsessionStorage) has been modified in the context of another document.
Connection events
Device orientation events
devicemotionSecure contextFired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available.
deviceorientationSecure contextFired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame.
deviceorientationabsoluteSecure contextFired when fresh data is available from the magnetometer orientation sensor about the current absolute orientation of the device as compared to the Earth coordinate frame.
Focus events
Gamepad events
gamepadconnectedFired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.
gamepaddisconnectedFired when the browser detects that a gamepad has been disconnected.
History events
hashchangeFired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the
#symbol).pagehideSent when the browser hides the current document while in the process of switching to displaying in its place a different document from the session's history. This happens, for example, when the user clicks the Back button or when they click the Forward button to move ahead in session history.
pagerevealFired when a document is first rendered, either when loading a fresh document from the network or activating a document (either fromback/forward cache (bfcache) orprerender).
pageshowSent when the browser makes the document visible due to navigation tasks, including not only when the page is first loaded, but also situations such as the user navigating back to the page after having navigated to another within the same tab.
pageswapFired when a document is about to be unloaded due to a navigation.
popstateFired when the active history entry changes.
Load & unload events
beforeunloadFired when the window, the document and its resources are about to be unloaded.
loadFired when the whole page has loaded, including all dependent resources such as stylesheets images.
unloadFired when the document or a child resource is being unloaded.
Manifest events
appinstalledFired when the browser has successfully installed a page as an application.
beforeinstallpromptFired when a user is about to be prompted to install a web application.
Messaging events
messageFired when the window receives a message, for example from a call to
Window.postMessage()from another browsing context.messageerrorFired when a
Windowobject receives a message that can't be deserialized.
Print events
afterprintFired after the associated document has started printing or the print preview has been closed.
beforeprintFired when the associated document is about to be printed or previewed for printing.
Promise rejection events
rejectionhandledSent every time a JavaScript
Promiseis rejected, regardless of whether or not there is a handler in place to catch the rejection.unhandledrejectionSent when a JavaScript
Promiseis rejected but there is no handler in place to catch the rejection.
Scroll events
scrollsnapchangeExperimentalFired on the scroll container at the end of a scrolling operation when a new scroll snap target has been selected.
scrollsnapchangingExperimentalFired on the scroll container when the browser determines a new scroll snap target is pending, i.e., it will be selected when the current scroll gesture ends.
Deprecated events
orientationchangeDeprecatedFired when the orientation of the device has changed.
vrdisplayactivateDeprecatedNon-standardFired when a display is able to be presented to.
vrdisplayconnectDeprecatedNon-standardFired when a compatible VR device has been connected to the computer.
vrdisplaydisconnectDeprecatedNon-standardFired when a compatible VR device has been disconnected from the computer.
vrdisplaydeactivateDeprecatedNon-standardFired when a display can no longer be presented to.
vrdisplaypresentchangeDeprecatedNon-standardFired when the presenting state of a VR device changes — i.e., goes from presenting to not presenting, or vice versa.
Bubbled events
Not all events that bubble can reach theWindow object. Only the following do and can be listened for on theWindow object:
abortauxclickbeforeinputbeforematchbeforetogglecancelcanplaycanplaythroughchangeclickclosecontextlostcontextmenucontextrestoredcopycuechangecutdblclickdragdragenddragenterdragleavedragoverdragstartdropdurationchangeemptiedendedformdatainputinvalidkeydownkeypresskeyuploadeddataloadedmetadataloadstartmousedownmouseentermouseleavemousemovemouseoutmouseovermouseuppastepauseplayplayingprogressratechangeresetscrollendsecuritypolicyviolationseekedseekingselectslotchangestalledsubmitsuspendtimeupdatetogglevolumechangewaitingwheel
Interfaces
SeeDOM Reference.
Listening for events on Window
HTML elements have three ways to listen for events:
- Add an event listener to the element using the
EventTarget.addEventListenermethod. - Assign an event handler to the element's
oneventnameproperty in JavaScript. - Add an
on-prefixed attribute to the element in the HTML.
To listen for events onWindow objects, in general, you can only use the first two methods, becauseWindow has no corresponding HTML element. However, there's a specific group of events whose listeners can be added to the<body> (or the deprecated<frameset>) element that's owned by theWindow's document, using the second or third methods. These events are:
afterprintbeforeprintbeforeunloadblurerrorfocushashchangelanguagechangeloadmessagemessageerrorofflineonlinepagehidepagerevealpageshowpageswappopstaterejectionhandledresizescrollstorageunhandledrejectionunload
This means the following are strictly equivalent:
window.onresize = (e) => console.log(e.currentTarget);document.body.onresize = (e) => console.log(e.currentTarget);<body onresize="console.log(event.currentTarget)"></body>In all three cases, you see theWindow object logged ascurrentTarget.
Specifications
| Specification |
|---|
| HTML> # the-window-object> |