跳转到主要内容

Window

{{APIRef("HTML DOM")}}

The Window interface represents a window containing a {{glossary("DOM")}}DOM document; the document property points to the DOM document loaded in that window.

A window for a given document can be obtained using the {{domxref("document.defaultView")}}defaultView property.

A global variable, window, representing the window in which the script is running, is exposed to JavaScript code.

The Window 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, the Window interface is a suitable place to include these items that need to be globally available. Many of these are documented in the JavaScript Reference and the DOM Reference.

In a tabbed browser, each tab is represented by its own Window object; the global window 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 as {{Domxref("Window.resizeTo", "resizeTo()")}} and {{Domxref("Window.innerHeight", "innerHeight")}}innerHeight. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.

{{InheritanceDiagram}}

Instance properties

This interface inherits properties from the {{domxref("EventTarget")}}EventTarget interface.

Note that properties which are objects (e.g., for overriding the prototype of built-in elements) are listed in a separate section below.

Deprecated properties

Instance methods

This interface inherits methods from the {{domxref("EventTarget")}}EventTarget interface.

Deprecated methods

Events

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface. In addition to the events listed below, many events can bubble from the {{domxref("Document")}}Document contained in the window object.

  • {{domxref("Window/error_event", "error")}}error
    • : Fired 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.
  • {{domxref("Window/languagechange_event", "languagechange")}}languagechange
    • : Fired at the global scope object when the user's preferred language changes.
  • {{domxref("Window/resize_event", "resize")}}resize
    • : Fired when the window has been resized.
  • {{domxref("Window/storage_event", "storage")}}storage
    • : Fired when a storage area (localStorage or sessionStorage) has been modified in the context of another document.

Connection events

  • {{domxref("Window/offline_event", "offline")}}offline
    • : Fired when the browser has lost access to the network and the value of navigator.onLine has switched to false.
  • {{domxref("Window/online_event", "online")}}online
    • : Fired when the browser has gained access to the network and the value of navigator.onLine has switched to true.

Device orientation events

  • {{domxref("Window.devicemotion_event", "devicemotion")}} {{SecureContext_Inline}}devicemotion
    • : Fired at a regular interval, indicating the amount of physical force of acceleration the device is receiving and the rate of rotation, if available.
  • {{domxref("Window.deviceorientation_event", "deviceorientation")}} {{SecureContext_Inline}}deviceorientation
    • : Fired when fresh data is available from the magnetometer orientation sensor about the current orientation of the device as compared to the Earth coordinate frame.
  • {{domxref("Window.deviceorientationabsolute_event", "deviceorientationabsolute")}} {{SecureContext_Inline}}deviceorientationabsolute
    • : Fired 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

  • {{domxref("Window/blur_event", "blur")}}blur
    • : Fired when the window has lost focus.
  • {{domxref("Window/focus_event", "focus")}}focus
    • : Fired when the window has gained focus.

Gamepad events

  • {{domxref("Window/gamepadconnected_event", "gamepadconnected")}}gamepadconnected
    • : Fired when the browser detects that a gamepad has been connected or the first time a button/axis of the gamepad is used.
  • {{domxref("Window/gamepaddisconnected_event", "gamepaddisconnected")}}gamepaddisconnected
    • : Fired when the browser detects that a gamepad has been disconnected.

History events

  • {{domxref("Window/hashchange_event", "hashchange")}}hashchange
    • : Fired when the fragment identifier of the URL has changed (the part of the URL beginning with and following the # symbol).
  • {{domxref("Window/pagehide_event", "pagehide")}}pagehide
    • : Sent 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.
  • {{domxref("Window.pagereveal_event", "pagereveal")}}pagereveal
    • : Fired when a document is first rendered, either when loading a fresh document from the network or activating a document (either from back/forward cache (bfcache) or prerender).
  • {{domxref("Window/pageshow_event", "pageshow")}}pageshow
    • : Sent 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.
  • {{domxref("Window.pageswap_event", "pageswap")}}pageswap
    • : Fired when a document is about to be unloaded due to a navigation.
  • {{domxref("Window/popstate_event", "popstate")}}popstate
    • : Fired when the active history entry changes.

Load & unload events

  • {{domxref("Window/beforeunload_event", "beforeunload")}}beforeunload
    • : Fired when the window, the document and its resources are about to be unloaded.
  • {{domxref("Window/load_event", "load")}}load
    • : Fired when the whole page has loaded, including all dependent resources such as stylesheets images.
  • {{domxref("Window/unload_event", "unload")}}unload
    • : Fired when the document or a child resource is being unloaded.

Manifest events

  • {{domxref("Window/appinstalled_event", "appinstalled")}}appinstalled
    • : Fired when the browser has successfully installed a page as an application.
  • {{domxref("Window/beforeinstallprompt_event", "beforeinstallprompt")}}beforeinstallprompt
    • : Fired when a user is about to be prompted to install a web application.

Messaging events

  • {{domxref("Window/message_event", "message")}}message
    • : Fired when the window receives a message, for example from a call to {{domxref("Window/postMessage", "Window.postMessage()")}} from another browsing context.
  • {{domxref("Window/messageerror_event", "messageerror")}}messageerror
    • : Fired when a Window object receives a message that can't be deserialized.

Print events

  • {{domxref("Window/afterprint_event", "afterprint")}}afterprint
    • : Fired after the associated document has started printing or the print preview has been closed.
  • {{domxref("Window/beforeprint_event", "beforeprint")}}beforeprint
    • : Fired when the associated document is about to be printed or previewed for printing.

Promise rejection events

  • {{domxref("Window/rejectionhandled_event", "rejectionhandled")}}rejectionhandled
    • : Sent every time a JavaScript {{jsxref("Promise")}}Promise is rejected, regardless of whether or not there is a handler in place to catch the rejection.
  • {{domxref("Window/unhandledrejection_event", "unhandledrejection")}}unhandledrejection
    • : Sent when a JavaScript {{jsxref("Promise")}}Promise is rejected but there is no handler in place to catch the rejection.

Scroll events

  • {{domxref("Window/scrollsnapchange_event", "scrollsnapchange")}} {{experimental_inline}}scrollsnapchange
    • : Fired on the scroll container at the end of a scrolling operation when a new scroll snap target has been selected.
  • {{domxref("Window/scrollsnapchanging_event", "scrollsnapchanging")}} {{experimental_inline}}scrollsnapchanging
    • : Fired 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

  • {{domxref("Window/orientationchange_event", "orientationchange")}} {{Deprecated_Inline}}orientationchange
    • : Fired when the orientation of the device has changed.
  • {{domxref("Window/vrdisplayactivate_event", "vrdisplayactivate")}} {{Deprecated_Inline}} {{Non-standard_Inline}}vrdisplayactivate
    • : Fired when a display is able to be presented to.
  • {{domxref("Window/vrdisplayconnect_event", "vrdisplayconnect")}} {{Deprecated_Inline}} {{Non-standard_Inline}}vrdisplayconnect
    • : Fired when a compatible VR device has been connected to the computer.
  • {{domxref("Window/vrdisplaydisconnect_event", "vrdisplaydisconnect")}} {{Deprecated_Inline}} {{Non-standard_Inline}}vrdisplaydisconnect
    • : Fired when a compatible VR device has been disconnected from the computer.
  • {{domxref("Window/vrdisplaydeactivate_event", "vrdisplaydeactivate")}} {{Deprecated_Inline}} {{Non-standard_Inline}}vrdisplaydeactivate
    • : Fired when a display can no longer be presented to.
  • {{domxref("Window/vrdisplaypresentchange_event", "vrdisplaypresentchange")}} {{Deprecated_Inline}} {{Non-standard_Inline}}vrdisplaypresentchange
    • : Fired 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 the Window object. Only the following do and can be listened for on the Window object:

  • abort
  • {{domxref("Element/auxclick_event", "auxclick")}}auxclick
  • {{domxref("Element/beforeinput_event", "beforeinput")}}beforeinput
  • {{domxref("Element/beforematch_event", "beforematch")}}beforematch
  • {{domxref("HTMLElement/beforetoggle_event", "beforetoggle")}}beforetoggle
  • cancel
  • {{domxref("HTMLMediaElement/canplay_event", "canplay")}}canplay
  • {{domxref("HTMLMediaElement/canplaythrough_event", "canplaythrough")}}canplaythrough
  • {{domxref("HTMLElement/change_event", "change")}}change
  • {{domxref("Element/click_event", "click")}}click
  • {{domxref("HTMLDialogElement/close_event", "close")}}close
  • {{domxref("HTMLCanvasElement/contextlost_event", "contextlost")}}contextlost
  • {{domxref("Element/contextmenu_event", "contextmenu")}}contextmenu
  • {{domxref("HTMLCanvasElement/contextrestored_event", "contextrestored")}}contextrestored
  • {{domxref("Element/copy_event", "copy")}}copy
  • {{domxref("HTMLTrackElement/cuechange_event", "cuechange")}}cuechange
  • {{domxref("Element/cut_event", "cut")}}cut
  • {{domxref("Element/dblclick_event", "dblclick")}}dblclick
  • {{domxref("HTMLElement/drag_event", "drag")}}drag
  • {{domxref("HTMLElement/dragend_event", "dragend")}}dragend
  • {{domxref("HTMLElement/dragenter_event", "dragenter")}}dragenter
  • {{domxref("HTMLElement/dragleave_event", "dragleave")}}dragleave
  • {{domxref("HTMLElement/dragover_event", "dragover")}}dragover
  • {{domxref("HTMLElement/dragstart_event", "dragstart")}}dragstart
  • {{domxref("HTMLElement/drop_event", "drop")}}drop
  • {{domxref("HTMLMediaElement/durationchange_event", "durationchange")}}durationchange
  • {{domxref("HTMLMediaElement/emptied_event", "emptied")}}emptied
  • {{domxref("HTMLMediaElement/ended_event", "ended")}}ended
  • {{domxref("HTMLFormElement/formdata_event", "formdata")}}formdata
  • {{domxref("Element/input_event", "input")}}input
  • {{domxref("HTMLElement/invalid_event", "invalid")}}invalid
  • {{domxref("Element/keydown_event", "keydown")}}keydown
  • {{domxref("Element/keypress_event", "keypress")}}keypress
  • {{domxref("Element/keyup_event", "keyup")}}keyup
  • {{domxref("HTMLMediaElement/loadeddata_event", "loadeddata")}}loadeddata
  • {{domxref("HTMLMediaElement/loadedmetadata_event", "loadedmetadata")}}loadedmetadata
  • {{domxref("HTMLMediaElement/loadstart_event", "loadstart")}}loadstart
  • {{domxref("Element/mousedown_event", "mousedown")}}mousedown
  • {{domxref("Element/mouseenter_event", "mouseenter")}}mouseenter
  • {{domxref("Element/mouseleave_event", "mouseleave")}}mouseleave
  • {{domxref("Element/mousemove_event", "mousemove")}}mousemove
  • {{domxref("Element/mouseout_event", "mouseout")}}mouseout
  • {{domxref("Element/mouseover_event", "mouseover")}}mouseover
  • {{domxref("Element/mouseup_event", "mouseup")}}mouseup
  • {{domxref("Element/paste_event", "paste")}}paste
  • {{domxref("HTMLMediaElement/pause_event", "pause")}}pause
  • {{domxref("HTMLMediaElement/play_event", "play")}}play
  • {{domxref("HTMLMediaElement/playing_event", "playing")}}playing
  • {{domxref("HTMLMediaElement/progress_event", "progress")}}progress
  • {{domxref("HTMLMediaElement/ratechange_event", "ratechange")}}ratechange
  • {{domxref("HTMLFormElement/reset_event", "reset")}}reset
  • {{domxref("Element/scrollend_event", "scrollend")}}scrollend
  • {{domxref("Element/securitypolicyviolation_event", "securitypolicyviolation")}}securitypolicyviolation
  • {{domxref("HTMLMediaElement/seeked_event", "seeked")}}seeked
  • {{domxref("HTMLMediaElement/seeking_event", "seeking")}}seeking
  • {{domxref("Element/select_event", "select")}}select
  • {{domxref("HTMLSlotElement/slotchange_event", "slotchange")}}slotchange
  • {{domxref("HTMLMediaElement/stalled_event", "stalled")}}stalled
  • {{domxref("HTMLFormElement/submit_event", "submit")}}submit
  • {{domxref("HTMLMediaElement/suspend_event", "suspend")}}suspend
  • {{domxref("HTMLMediaElement/timeupdate_event", "timeupdate")}}timeupdate
  • {{domxref("HTMLElement/toggle_event", "toggle")}}toggle
  • {{domxref("HTMLMediaElement/volumechange_event", "volumechange")}}volumechange
  • {{domxref("HTMLMediaElement/waiting_event", "waiting")}}waiting
  • {{domxref("Element/wheel_event", "wheel")}}wheel

Interfaces

See DOM Reference.

Listening for events on Window

HTML elements have three ways to listen for events:

  • Add an event listener to the element using the {{domxref("EventTarget.addEventListener")}}addEventListener method.
  • Assign an event handler to the element's oneventname property in JavaScript.
  • Add an on-prefixed attribute to the element in the HTML.

To listen for events on Window objects, in general, you can only use the first two methods, because Window has no corresponding HTML element. However, there's a specific group of events whose listeners can be added to the {{HTMLElement("body")}}body (or the deprecated {{HTMLElement("frameset")}}frameset) element that's owned by the Window's document, using the second or third methods. These events are:

  • afterprint
  • beforeprint
  • beforeunload
  • blur
  • error
  • focus
  • hashchange
  • languagechange
  • load
  • message
  • messageerror
  • offline
  • online
  • pagehide
  • pagereveal
  • pageshow
  • pageswap
  • popstate
  • rejectionhandled
  • resize
  • scroll
  • storage
  • unhandledrejection
  • unload

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 the Window object logged as currentTarget.

Specifications

{{Specifications}}

Browser compatibility

{{Compat}}