Class Window
- Namespace
- CSharpToJavaScript.APIs.JS
- Assembly
- CSharpToJavaScript.dll
The Window interface represents a window containing a DOM document; the document property points to the DOM document loaded in that window.
[Value("Window")]
public class Window : EventTarget
- Inheritance
-
Window
- Inherited Members
Remarks
A window for a given document can be obtained using the 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 ResizeTo(long, long) and InnerHeight. Generally, anything that can't reasonably pertain to a tab pertains to the window instead.
Constructors
Window()
public Window()
Properties
ClientInformation
[Value("clientInformation")]
public Navigator ClientInformation { get; }
Property Value
Closed
The Window.closed read-only property indicates whether
the referenced window is closed or not.
[Value("closed")]
public bool Closed { get; }
Property Value
- bool
A boolean value. Possible values:
Remarks
CookieStore
The cookieStore read-only property of the Window interface returns a reference to the CookieStore object for the current document context. This is an entry point for the Cookie Store API.
[Value("cookieStore")]
public CookieStore CookieStore { get; }
Property Value
- CookieStore
A CookieStore object instance.
Remarks
Credentialless
NOTE
Experimentalwindow.credentialless read-only property returns a boolean that indicates whether the current document was loaded inside a credentialless iframe, meaning that it is loaded in a new, ephemeral context.
[Value("credentialless")]
public bool Credentialless { get; }
Property Value
- bool
A boolean. A value of
trueindicates that the document was loaded inside a credentialless<iframe>;falseindicates that it was not.
Remarks
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 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 for a deeper explanation.
CustomElements
The customElements read-only property of the Window interface returns a reference to the CustomElementRegistry object, which can be used to register new custom elements and get information about previously registered custom elements.
[Value("customElements")]
public CustomElementRegistry CustomElements { get; }
Property Value
Remarks
DevicePixelRatio
The devicePixelRatio of Window interface returns the ratio of the resolution in physical pixels to the resolution in CSS pixels for the current display device.
[Value("devicePixelRatio")]
public Number DevicePixelRatio { get; }
Property Value
- Number
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 adevicePixelRatiovalue greater than 2.
Remarks
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.
Page zooming affects the value of devicePixelRatio. When a page is zoomed in (made larger), the size of a CSS pixel increases, and so the devicePixelRatio value increases.
Pinch-zooming does not affect devicePixelRatio, because this magnifies the page without changing the size of a 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 MatchMedia(string) 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.
-Media queries
-Using media queries
-CSS resolution media query
-The image-resolution property
Document
window.document returns a reference to the document contained in the window.
[Value("document")]
public Document Document { get; }
Property Value
Remarks
DocumentPictureInPicture
NOTE
ExperimentaldocumentPictureInPicture read-only property of theWindow interface returns a reference to the DocumentPictureInPicture object for the current document context.
[Value("documentPictureInPicture")]
public DocumentPictureInPicture DocumentPictureInPicture { get; }
Property Value
- DocumentPictureInPicture
A DocumentPictureInPicture object instance.
Remarks
-{{domxref("Document Picture-in-Picture API", "Document Picture-in-Picture API", "", "nocode")}}
-Using the Document Picture-in-Picture API
Event
IMPORTANT
Deprecatedevent returns the Event which is currently being handled by the site's code. Outside the context of an event handler, the value is always undefined.
[Value("event")]
public Union25 Event { get; }
Property Value
Remarks
You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.
NOTE
This property can be fragile, in that there may be situations in which the returned
Eventis not the expected value. In addition,Window.eventis not accurate for events dispatched within shadow tree.
External
IMPORTANT
Deprecatedexternal property of the Window API returns an instance of the External interface, which was intended to contain functions related to adding external search providers to the browser. However, this is now deprecated, and the contained methods are now dummy functions that do nothing as per spec.
[Value("external")]
public External External { get; }
Property Value
Remarks
Fence
NOTE
Experimentalfence read-only property of the Window interface returns a Fence object instance for the current document context.
[Value("fence")]
public Fence? Fence { get; }
Property Value
- Fence
A Fence object instance, or
nullif the document context does not have access to a Fence object.
Remarks
Fence objects are only available to documents embedded inside {{htmlelement("fencedframe")}}s (loaded via FencedFrameConfigs) or {{htmlelement("iframe")}}s (loaded via opaque URNs).
NOTE
See How do
<fencedframe>s work? for some description aroundFencedFrameConfigs and opaque URNs.
-Fenced frames on privacysandbox.google.com
-The Privacy Sandbox on privacysandbox.google.com
FrameElement
The Window.frameElement property
returns the element (such as iframe or object)
in which the window is embedded.
[Value("frameElement")]
public Element? FrameElement { get; }
Property Value
- Element
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
origin, the value isnullinstead.
Remarks
NOTE
Despite this property's name, it works for documents embedded
within any embedding point, including object,
iframe, or embed.
-Frames returns an array-like object, listing the direct
sub-frames of the current window.
-Parent returns the parent window, which is the window
containing the frameElement of the child window.
Frames
Returns the window itself, which is an array-like object, listing the direct sub-frames
of the current window.
[Value("frames")]
public Window Frames { get; }
Property Value
- Window
A list of frame objects. It is similar to an
array in that it has alengthproperty and its items can be accessed
using the[i]notation.
Remarks
History
The Window.history read-only property returns a reference to the History object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in).
[Value("history")]
public History History { get; }
Property Value
Remarks
See Manipulating the browser history for examples and details. In particular, that article explains security features of the PushState(dynamic, string, string?) and ReplaceState(dynamic, string, string?) methods that you should be aware of before using them.
InnerHeight
The read-only innerHeight property of the
Window interface returns the interior height of the window in pixels,
including the height of the horizontal scroll bar, if present.
[Value("innerHeight")]
public long InnerHeight { get; }
Property Value
- long
An integer value indicating the window's layout viewport height in pixels. The property
is read only and has no default value.To change the height of the window, call one of its resize methods, such as
ResizeTo(long, long) or ResizeBy(long, long).
Remarks
The value of innerHeight is taken from the height of the window's
layout viewport. The width can be obtained using the
InnerWidth property.
InnerWidth
The read-only Window property innerWidth returns the interior width of the window in pixels (that is, the width of the window's layout viewport). That includes the width of the vertical scroll bar, if one is present.
[Value("innerWidth")]
public long InnerWidth { get; }
Property Value
- long
An integer value indicating the width of the window's layout viewport in pixels. This
property is read-only, and has no default value.To change the window's width, use one of the Window methods for resizing
windows, such as ResizeBy(long, long) or
ResizeTo(long, long).
Remarks
Similarly, the interior height of the window (that is, the height of the layout viewport) can be obtained using the InnerHeight property. That measurement also accounts for the height of the horizontal scroll bar, if it is visible.
LaunchQueue
NOTE
ExperimentallaunchQueue read-only property of the Window interface provides access to the LaunchQueue class, which allows custom launch navigation handling to be implemented in a progressive web app (PWA), with the handling context signified by the launch_handler manifest field client_mode value.
[Value("launchQueue")]
public LaunchQueue LaunchQueue { get; }
Property Value
- LaunchQueue
A LaunchQueue object instance.
Remarks
The custom launch navigation handling functionality is controlled by the properties of the LaunchParams object passed into the SetConsumer(LaunchConsumer) callback function.
-{{domxref("Launch Handler API", "Launch Handler API", "", "nocode")}}
-Launch Handler API: Control how your app is launched
-Musicr 2.0 demo app
Length
[Value("length")]
public ulong Length { get; }
Property Value
- ulong
A number.
Remarks
Location
The Window.location read-only property returns a Location object with information about the current location of the document.
[Value("location")]
public Location Location { get; }
Property Value
Remarks
Though Window.location is a read-only Location object, you can also assign a string to it.
This means that you can work with location as if it were a string in most cases:location = 'http://www.example.com' is a synonym of location.href = 'http://www.example.com'.
See Location for all available properties.
-The interface of the returned value, Location
-A similar information, but attached to the document,
Location
-Manipulating the browser history
-Windowhashchange
Locationbar
Returns the locationbar object.
[Value("locationbar")]
public BarProp Locationbar { get; }
Property Value
- BarProp
An object containing a single property:
Remarks
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.
Menubar
Returns the menubar object.
[Value("menubar")]
public BarProp Menubar { get; }
Property Value
- BarProp
An object containing a single property:
Remarks
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.
Name
The Window.name property
gets/sets the name of the window's browsing context.
[Value("name")]
public string Name { get; set; }
Property Value
- string
A string.
Remarks
Navigation
NOTE
Experimentalnavigation read-only property of the Window interface returns the current window's associated Navigation object.
[Value("navigation")]
public Navigation Navigation { get; }
Property Value
- Navigation
A Navigation object instance.
Remarks
This is the entry point for the {{domxref("Navigation API", "", "", "nocode")}}.
-Modern client-side routing: the Navigation API
-Navigation API explainer
-Navigation API live demo (view demo source)
Navigator
The Window.navigator read-only property returns a
reference to the Navigator object, which has methods and properties about
the application running the script.
[Value("navigator")]
public Navigator Navigator { get; }
Property Value
Remarks
Onappinstalled
[Value("onappinstalled")]
public EventHandlerNonNull Onappinstalled { get; set; }
Property Value
Onbeforeinstallprompt
[Value("onbeforeinstallprompt")]
public EventHandlerNonNull Onbeforeinstallprompt { get; set; }
Property Value
Ondevicemotion
[Value("ondevicemotion")]
public EventHandlerNonNull Ondevicemotion { get; set; }
Property Value
Ondeviceorientation
[Value("ondeviceorientation")]
public EventHandlerNonNull Ondeviceorientation { get; set; }
Property Value
Ondeviceorientationabsolute
[Value("ondeviceorientationabsolute")]
public EventHandlerNonNull Ondeviceorientationabsolute { get; set; }
Property Value
Onorientationchange
[Value("onorientationchange")]
public EventHandlerNonNull Onorientationchange { get; set; }
Property Value
Opener
The Window interface'sopener property returns a reference to the window that
opened the window, either with Open(string, string, string), or by navigating
a link with a target attribute.
[Value("opener")]
public dynamic Opener { get; set; }
Property Value
- dynamic
A Window-like object referring to the window that opened the current
window (using Open(string, string, string), or by a link withtargetattribute set). If this window was not opened by being linked to or created by
another, returnsnull.If the opener is not on the same origin as the current page, functionality of the
opener object is limited. For example, variables and functions on the window object are
not accessible. However, navigation of the opener window is possible, which means that
the opened page can open a URL in the original tab or window. In some cases, this makes
phishing attacks possible, where a trusted page that is opened in the original window is
replaced by a phishing page by the newly opened page.To be exact, for cross-origin opener objects, the following properties are available:In addition, there are a few properties:then, {{jsxref("Symbol/toStringTag", "[Symbol.toStringTag]")}}, {{jsxref("Symbol/hasInstance", "[Symbol.hasInstance]")}}, {{jsxref("Symbol/isConcatSpreadable", "[Symbol.isConcatSpreadable]")}}, which are used by various JavaScript operations. These properties have valuesundefined. All other properties generate aSecurityErrorDOMException when accessed.In the following cases, the browser does not populatewindow.opener, but
leaves itnull:
Remarks
In other words, if window A opens window B,B.opener returns A.
Orientation
IMPORTANT
Deprecated[Value("orientation")]
public Number Orientation { get; }
Property Value
Remarks
Its only possible values are -90, 0, 90, and 180. Positive values are counterclockwise; negative values are clockwise.
This property is deprecated. Use the Orientation property instead, available on the Screen property.
OriginAgentCluster
The originAgentCluster read-only property of the Window interface returns true if this window belongs to an origin-keyed agent cluster: this means that the operating system has provided dedicated resources (for example an operating system process) to this window's origin that are not shared with windows from other origins.
[Value("originAgentCluster")]
public bool OriginAgentCluster { get; }
Property Value
Remarks
Otherwise this property returns false.
Windows that are part of an origin-keyed agent cluster are subjects to some additional restrictions, compared with windows that are not. In particular, they cannot:
To request that the browser assign this window to an origin-keyed agent cluster, the server must send the Origin-Agent-Cluster response header.
Note that the origin-keyed agent cluster feature is only supported in Secure Context. If a site is not a secure context, the window.originAgentCluster will always return false.
-Origin-Agent-Cluster HTTP response header
-Requesting performance isolation with the Origin-Agent-Cluster header
OuterHeight
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.
[Value("outerHeight")]
public long OuterHeight { get; }
Property Value
Remarks
OuterWidth
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.
[Value("outerWidth")]
public long OuterWidth { get; }
Property Value
Remarks
PageXOffset
[Value("pageXOffset")]
public Number PageXOffset { get; }
Property Value
PageYOffset
[Value("pageYOffset")]
public Number PageYOffset { get; }
Property Value
Parent
The Window.parent property is a reference to the parent
of the current window or subframe.
[Value("parent")]
public Window? Parent { get; }
Property Value
Remarks
If a window does not have a parent, its parent property is a reference to
itself.
When a window is loaded in an iframe, object, or
frame, its parent is the window with the element embedding the
window.
-FrameElement returns the specific element (such as<iframe>) the window is embedded into.
-Top returns a reference to the top-level window.
Personalbar
Returns the personalbar object.
[Value("personalbar")]
public BarProp Personalbar { get; }
Property Value
- BarProp
An object containing a single property:
Remarks
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.
PortalHost
[Value("portalHost")]
public PortalHost? PortalHost { get; }
Property Value
Screen
The Window property screen returns a
reference to the screen object associated with the window. The screen
object, implementing the Screen interface, is a special object for
inspecting properties of the screen on which the current window is being rendered.
[Value("screen")]
public Screen Screen { get; }
Property Value
Remarks
ScreenLeft
The Window.screenLeft read-only property returns the
horizontal distance, in CSS pixels, from the left border of the user's browser viewport
to the left side of the screen.
[Value("screenLeft")]
public long ScreenLeft { get; }
Property Value
- long
A number equal to the number of CSS pixels from the left edge of the browser viewport
to the left edge of the screen.
Remarks
NOTE
screenLeftis an alias of the older
ScreenX property.screenLeftwas originally
supported only in IE but was introduced everywhere due to popularity.
ScreenTop
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.
[Value("screenTop")]
public long ScreenTop { get; }
Property Value
- long
A number equal to the number of CSS pixels from the top edge of the browser viewport to
the top edge of the screen.
Remarks
NOTE
screenTopis an alias of the older
ScreenY property.screenTopwas originally
supported only in IE but was introduced everywhere due to popularity.
ScreenX
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.
[Value("screenX")]
public long ScreenX { get; }
Property Value
- long
A number equal to the number of CSS pixels from the left edge of the browser viewport
to the left edge of the screen.
Remarks
NOTE
An alias of
screenXwas implemented across modern
browsers in more recent times — ScreenLeft. This was originally
supported only in IE but was introduced everywhere due to popularity.
ScreenY
The Window.screenY read-only property returns the vertical distance, in CSS pixels, of the top border of the user's browser viewport to the top edge of the screen.
[Value("screenY")]
public long ScreenY { get; }
Property Value
- long
A number equal to the number of CSS pixels from the top edge of the browser viewport to the top edge of the screen.
Remarks
NOTE
An alias of
screenYwas implemented across modern browsers in more recent times — ScreenTop. This was originally supported only in IE but was introduced everywhere due to popularity.
ScrollX
The read-only scrollX property of the Window interface returns the number of pixels by which the document is currently scrolled horizontally. This value is subpixel precise in modern browsers, meaning that it isn't necessarily a whole number. You can get the number of pixels the document is scrolled vertically from the ScrollY property.
[Value("scrollX")]
public Number ScrollX { get; }
Property Value
- Number
A double-precision floating-point value indicating the number of pixels by which the document is currently scrolled horizontally from the origin, where a positive value means the content is scrolled to the right (to reveal more content to the right). In more technical terms,
scrollXreturns the X coordinate of the left edge of the current viewport. If the document isn't scrolled at all left or right, thenscrollXis 0. If there is no viewport, the returned value is 0. If the document is rendered on a subpixel-precise device, then the returned value is also subpixel-precise and may contain a decimal component.
It's possible forNOTE
If you need an integer value, you can use MathRound to round it off.scrollXto be negative if the document can be scrolled to the left from the initial containing block. For example, if the document is right-to-left and content grows to the left.Safari responds to overscrolling by updatingscrollXbeyond the maximum scroll position (unless the default "bounce" effect is disabled, such as by setting overscroll-behavior tonone), while Chrome and Firefox do not.This property is read-only. To scroll the window to a particular place, use Scroll(ScrollToOptions).
Remarks
ScrollY
The read-only scrollY property of the Window interface returns the number of pixels by which 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 ScrollX property.
[Value("scrollY")]
public Number ScrollY { get; }
Property Value
- Number
A double-precision floating-point value indicating the number of pixels by which the document is currently scrolled vertically from the origin, where a positive value means the content is scrolled down (to reveal more content to the bottom). In more technical terms,
scrollYreturns the Y coordinate of the top edge of the current viewport. If the document isn't scrolled at all top or down, thenscrollYis 0. If there is no viewport, the returned value is 0. If the document is rendered on a subpixel-precise device, then the returned value is also subpixel-precise and may contain a decimal component.
Safari responds to overscrolling by updatingNOTE
If you need an integer value, you can use MathRound to round it off.scrollYbeyond the maximum scroll position (unless the default "bounce" effect is disabled, such as by setting overscroll-behavior tonone), while Chrome and Firefox do not. For example,scrollYmay be negative on Safari just by continuing to scroll up when the document is already at the top.This property is read-only. To scroll the window to a particular place, use Scroll(ScrollToOptions).
Remarks
Scrollbars
Returns the scrollbars object.
[Value("scrollbars")]
public BarProp Scrollbars { get; }
Property Value
- BarProp
An object containing a single property:
Remarks
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.
Self
The Window.self read-only property returns the window itself, as a 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 Self).
[Value("self")]
public Window Self { get; }
Property Value
- Window
A WindowProxy object.
Remarks
-Its Worker equivalent, Self.
SharedStorage
NOTE
ExperimentalsharedStorage property returns the WindowSharedStorage object for the current origin. This is the main entry point for writing data to shared storage using the Shared Storage API.
[Value("sharedStorage")]
public SharedStorage? SharedStorage { get; }
Property Value
- SharedStorage
A WindowSharedStorage object instance.
Remarks
NOTE
sharedStorageis not available inside workers. It is implemented by Window and is also available in shared storage worklets (see SharedStorage, which returns WorkletSharedStorage).
-WindowSharedStorage
-Shared Storage API
SpeechSynthesis
The speechSynthesis read-only property of the Window object returns a SpeechSynthesis object, which is the entry point into using Web Speech API speech synthesis functionality.
[Value("speechSynthesis")]
public SpeechSynthesis SpeechSynthesis { get; }
Property Value
- SpeechSynthesis
A SpeechSynthesis object.
Remarks
Status
IMPORTANT
Deprecatedstatus property of theWindow 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 thestatus bar.
[Value("status")]
public string Status { get; set; }
Property Value
- string
A string.
Remarks
Statusbar
Returns the statusbar object.
[Value("statusbar")]
public BarProp Statusbar { get; }
Property Value
- BarProp
An object containing a single property:
Remarks
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.
Toolbar
Returns the toolbar object.
[Value("toolbar")]
public BarProp Toolbar { get; }
Property Value
- BarProp
An object containing a single property:
Remarks
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.
Top
Returns a reference to the topmost window in the window hierarchy.
[Value("top")]
public Window? Top { get; }
Property Value
- Window
The reference to the topmost window.
Remarks
Viewport
[Value("viewport")]
public Viewport Viewport { get; }
Property Value
VisualViewport
The visualViewport read-only property of the Window interface returns a VisualViewport object representing the visual viewport for a given window, or null if current document is not fully active.
[Value("visualViewport")]
public VisualViewport? VisualViewport { get; }
Property Value
- VisualViewport
A VisualViewport object.
Remarks
_window
The window property of a Window object points to the window object itself.
[Value("window")]
public Window _window { get; }
Property Value
Remarks
Thus, the following expressions all return the same window object:
In web pages, the window object is also a global object. This means:
The point of having the window property refer to the object itself, was likely to make it easy to refer to the global object. Otherwise, you'd have to do a manual let window = this; assignment at the top of your script.
Another reason, is that without this property you wouldn't be able to write, for example, Open(string, string, string). You'd have to use open('https://google.com/') instead.
Yet another reason to use this property, is for libraries which wish to offer OOP-versions, and non-OOP versions (especially JavaScript modules). For example, if we refer to "this.window.location.href", a JavaScript module could define a property called "window" inside of a class it defined (since no global "window" variable exists for it by default) which could be created after passing in a window object to the module class' constructor. Thus, "this.window" inside of its functions would refer to that window object. In the non-namespaced version, "this.window" would refer back to "window", and also be able to readily get the document location. Another advantage, is that the objects of such a class (even if the class were defined outside of a module) could change their reference to the window at will, they would not be able to do this if they had hard-coded a reference to "window". The default in the class could still be set as the current window object.
Methods
Alert()
window.alert() instructs the browser to display a dialog with an optional message, and to wait until the user dismisses the dialog.
[Value("alert")]
public GlobalObject.Undefined Alert()
Returns
Remarks
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.
-dialog element
-Confirm(string)
-Prompt(string, string)
Alert(string)
window.alert() instructs the browser to display a dialog with an optional message, and to wait until the user dismisses the dialog.
[Value("alert")]
public GlobalObject.Undefined Alert(string message)
Parameters
messagestring
Returns
Remarks
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.
-dialog element
-Confirm(string)
-Prompt(string, string)
Blur()
IMPORTANT
DeprecatedWindow.blur() method does nothing.
[Value("blur")]
public GlobalObject.Undefined Blur()
Returns
Remarks
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 thedom.disable_window_flippreference.
CancelIdleCallback(ulong)
The window.cancelIdleCallback() method cancels a callback
previously scheduled with RequestIdleCallback(IdleRequestCallback, IdleRequestOptions).
[Value("cancelIdleCallback")]
public GlobalObject.Undefined CancelIdleCallback(ulong handle)
Parameters
handleulong
Returns
Remarks
CaptureEvents()
IMPORTANT
DeprecatedWindow.captureEvents() method does nothing. Its original behavior has been removed from the specification, but the method itself has been retained so as not to break code that calls it.
[Value("captureEvents")]
public GlobalObject.Undefined CaptureEvents()
Returns
Remarks
Close()
The Window.close() method closes the current window, or
the window on which it was called.
[Value("close")]
public GlobalObject.Undefined Close()
Returns
Remarks
Windows are script-closable if they were created by web content. This generally includes:
Windows opened by browser UI actions — such as right-click → Open in new tab, Ctrl+Click, Shift+Click, or middle-click — are often not script-closable. They may only be closed if they have not been navigated (history length remains 1). Calling close() otherwise typically shows a console warning: Scripts may not close windows that were not opened by script.
Note also that close() has no effect when called on Window
objects returned byHTMLIFrameElement.contentWindow.
Confirm(string)
window.confirm() instructs the browser to display a dialog with an optional message, and to wait until the user either confirms or cancels the dialog.
[Value("confirm")]
public bool Confirm(string message = null)
Parameters
messagestring
Returns
- bool
A boolean indicating whether OK (
true) or Cancel (false) was selected.
If a browser is ignoring in-page dialogs, then the returned value is alwaysfalse.
Remarks
Under some conditions — for example, when the user switches tabs — the browser may not actually display a dialog, or may not wait for the user to confirm or cancel the dialog.
-dialog element
-Alert()
-Prompt(string, string)
-Never Use a Warning When you Mean Undo on A List Apart (2017)
Focus()
Makes a request to bring the window to the front. It may fail due to user settings and the window isn't guaranteed to be frontmost before this method returns.
[Value("focus")]
public GlobalObject.Undefined Focus()
Returns
Remarks
GetComputedStyle(Element, string?)
TheWindow.getComputedStyle() method returns an object
containing the values of all CSS properties of an element, after applying active
stylesheets and resolving any basic computation those values may contain.
[Value("getComputedStyle")]
public CSSStyleDeclaration GetComputedStyle(Element elt, string? pseudoElt = null)
Parameters
Returns
- CSSStyleDeclaration
A live CSSStyleDeclaration object, which updates automatically when the element's styles are changed.Note that:The returned object is the same CSSStyleDeclaration type as the object returned from the element's HTMLElementstyle property. However, the two objects have different purposes:
Remarks
Individual CSS property values are accessed through APIs provided by the returned CSSStyleDeclaration object, or by indexing with CSS property names. The values returned by getComputedStyle are resolved values.
-Window.GetDefaultComputedStyle
-GetPropertyValue(string)
-ComputedStyleMap()
-Resolved value
GetDigitalGoodsService(string)
[Value("getDigitalGoodsService")]
public Task<DigitalGoodsService> GetDigitalGoodsService(string serviceProvider)
Parameters
serviceProviderstring
Returns
GetScreenDetails()
NOTE
ExperimentalgetScreenDetails() method of theWindow interface returns a {{jsxref("Promise")}} that fulfills with a ScreenDetails object instance representing the details of all the screens available to the user's device.
[Value("getScreenDetails")]
public Task<ScreenDetails> GetScreenDetails()
Returns
- Task<ScreenDetails>
A {{jsxref("Promise")}} that fulfills with a ScreenDetails object instance.
Remarks
GetSelection()
The getSelection() method of the Window interface returns the Selection object associated with the window's Document, representing the range of text selected by the user or the current position of the caret.
[Value("getSelection")]
public Selection? GetSelection()
Returns
- Selection
A Selection object, or
nullif the associated document has no browsing context (for example, the window is an iframe that is not attached to a document).When called on an iframe that is not displayed (e.g., wheredisplay: noneis set) Firefox returnsnull, whereas other browsers returns a Selection object with Type set toNone.
Remarks
MatchMedia(string)
The Window interface's matchMedia() method
returns a new MediaQueryList object that can then be used to determine if
the Document matches the media query string,
as well as to monitor the document to detect when it matches (or stops matching) that
media query.
[Value("matchMedia")]
public MediaQueryList MatchMedia(string query)
Parameters
querystring
Returns
- MediaQueryList
A new 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.
Remarks
MoveBy(long, long)
The moveBy() method of the Window
interface moves the current window by a specified amount.
[Value("moveBy")]
public GlobalObject.Undefined MoveBy(long x, long y)
Parameters
Returns
Remarks
NOTE
This function moves the window relative to its current
location. In contrast, MoveTo(long, long) moves the window to an absolute
location.
MoveTo(long, long)
The moveTo() method of the Window
interface moves the current window to the specified coordinates.
[Value("moveTo")]
public GlobalObject.Undefined MoveTo(long x, long y)
Parameters
Returns
Remarks
NOTE
This function moves the window to an absolute location. In
contrast, MoveBy(long, long) moves the window relative to its current
location.
Navigate(SpatialNavigationDirection)
[Value("navigate")]
public GlobalObject.Undefined Navigate(SpatialNavigationDirection dir)
Parameters
Returns
Open(string, string, string)
The open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, a tab, a window, or an iframe) under a specified name.
[Value("open")]
public Window? Open(string url = null, string target = null, string features = null)
Parameters
Returns
- Window
If the browser successfully opens the new browsing context, a
WindowProxyobject is returned.
The returned reference can be used to access properties and methods of the new context as long as it complies with the same-origin policy security requirements.If the {{httpheader("Cross-Origin-Opener-Policy")}} HTTP header is being used, and the document policies are such that the document is opened in a new {{glossary("Browsing context","browsing context group")}}, references to the opened window are severed and the returned object will indicate that the opened window is closed (Closed istrue).nullis returned if the browser fails to open the new browsing context, for example because it was blocked by a browser popup blocker.
Remarks
-target attribute documentation:-<a>
-<form>
-window.close()
-window.closed
-window.focus()
-window.opener
-rel="opener" and rel="noopener"
-Same-origin policy
PostMessage(dynamic, WindowPostMessageOptions)
The window.postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.
[Value("postMessage")]
public GlobalObject.Undefined PostMessage(dynamic message, WindowPostMessageOptions options = null)
Parameters
messagedynamicoptionsWindowPostMessageOptions
Returns
Remarks
Normally, scripts on different pages are allowed to access each other if and only if the pages they originate from share the same origin (also known as the "same-origin policy"). window.postMessage() provides a controlled mechanism to securely circumvent this restriction (if used properly).
Furthermore, an accessing script must have obtained the window object of the accessed document beforehand. This can occur through methods such as window.open() for popups or iframe.contentWindow for iframes.
Broadly, one window may obtain a reference to another (e.g., via targetWindow = window.opener), and then dispatch a MessageEvent on it with targetWindow.postMessage(). The receiving window is then free to handle this event as needed. The arguments passed to window.postMessage() (i.e., the "message") are exposed to the receiving window through the event object.
-Domain
-CustomEvent
-BroadcastChannel - For same-origin communication.
PostMessage(dynamic, string, List<Object>)
The window.postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.
[Value("postMessage")]
public GlobalObject.Undefined PostMessage(dynamic message, string targetOrigin, List<Object> transfer = null)
Parameters
Returns
Remarks
Normally, scripts on different pages are allowed to access each other if and only if the pages they originate from share the same origin (also known as the "same-origin policy"). window.postMessage() provides a controlled mechanism to securely circumvent this restriction (if used properly).
Furthermore, an accessing script must have obtained the window object of the accessed document beforehand. This can occur through methods such as window.open() for popups or iframe.contentWindow for iframes.
Broadly, one window may obtain a reference to another (e.g., via targetWindow = window.opener), and then dispatch a MessageEvent on it with targetWindow.postMessage(). The receiving window is then free to handle this event as needed. The arguments passed to window.postMessage() (i.e., the "message") are exposed to the receiving window through the event object.
-Domain
-CustomEvent
-BroadcastChannel - For same-origin communication.
Print()
Opens the print dialog to print the current document.
[Value("print")]
public GlobalObject.Undefined Print()
Returns
Remarks
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.
-Printing
-Window.Beforeprint event
-Window.Afterprint event
Prompt(string, string)
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.
[Value("prompt")]
public string? Prompt(string message = null, string default_ = null)
Parameters
Returns
- string
A string containing the text entered by the user, or
null.
Remarks
Under some conditions (when the user switches tabs, for example) the browser may not display a dialog, or may not wait for the user to submit text or to cancel the dialog.
-dialog element
-Alert()
-Confirm(string)
-Never Use a Warning When you Mean Undo on A List Apart (2017)
QueryLocalFonts(QueryOptions)
NOTE
Experimentalwindow.queryLocalFonts() method returns a {{jsxref("Promise")}} that fulfills with an array of FontData objects representing the font faces available locally.
[Value("queryLocalFonts")]
public Task<List<FontData>> QueryLocalFonts(QueryOptions options = null)
Parameters
optionsQueryOptions
Returns
- Task<List<FontData>>
A {{jsxref("Promise")}} that fulfills with an array of FontData objects representing the font faces available locally.
Remarks
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 set on your server.
-{{domxref("Local Font Access API", "Local Font Access API", "", "nocode")}}
-Use advanced typography with local fonts
-@font-face
ReleaseEvents()
IMPORTANT
Deprecated[Value("releaseEvents")]
public GlobalObject.Undefined ReleaseEvents()
Returns
Remarks
RequestIdleCallback(IdleRequestCallback, IdleRequestOptions)
The window.requestIdleCallback() method queues a function
to be called during a browser's idle periods. This enables developers to perform
background and low priority work on the main thread, without impacting
latency-critical events such as animation and input response. Functions are generally
called in first-in-first-out order; however, callbacks which have a timeout
specified may be called out-of-order if necessary in order to run them before the
timeout elapses.
[Value("requestIdleCallback")]
public ulong RequestIdleCallback(IdleRequestCallback callback, IdleRequestOptions options = null)
Parameters
callbackIdleRequestCallbackoptionsIdleRequestOptions
Returns
- ulong
An ID which can be used to cancel the callback by passing it into the
CancelIdleCallback(ulong) method.
Remarks
You can call requestIdleCallback() within an idle callback function to
schedule another callback to take place no sooner than the next pass through the event
loop.
NOTE
A
timeoutoption is strongly recommended for required work,
as otherwise it's possible multiple seconds will elapse before the callback is fired.
-CancelIdleCallback(ulong)
-IdleDeadline
-Window.SetTimeout
-Window.SetInterval
-Window.RequestAnimationFrame
ResizeBy(long, long)
The Window.resizeBy() method resizes the current window
by a specified amount.
[Value("resizeBy")]
public GlobalObject.Undefined ResizeBy(long x, long y)
Parameters
Returns
Remarks
ResizeTo(long, long)
The Window.resizeTo() method dynamically resizes the
window.
[Value("resizeTo")]
public GlobalObject.Undefined ResizeTo(long width, long height)
Parameters
Returns
Remarks
Scroll(ScrollToOptions)
The Window.scroll() method scrolls the window to a
particular place in the document.
[Value("scroll")]
public GlobalObject.Undefined Scroll(ScrollToOptions options = null)
Parameters
optionsScrollToOptions
Returns
Remarks
-Window.ScrollByLines
-Window.ScrollByPages
-ScrollIntoView(Union21)
Scroll(double, double)
The Window.scroll() method scrolls the window to a
particular place in the document.
[Value("scroll")]
public GlobalObject.Undefined Scroll(double x, double y)
Parameters
Returns
Remarks
-Window.ScrollByLines
-Window.ScrollByPages
-ScrollIntoView(Union21)
ScrollBy(ScrollToOptions)
The Window.scrollBy() method scrolls the document in the
window by the given amount.
[Value("scrollBy")]
public GlobalObject.Undefined ScrollBy(ScrollToOptions options = null)
Parameters
optionsScrollToOptions
Returns
Remarks
ScrollBy(double, double)
The Window.scrollBy() method scrolls the document in the
window by the given amount.
[Value("scrollBy")]
public GlobalObject.Undefined ScrollBy(double x, double y)
Parameters
Returns
Remarks
ScrollTo(ScrollToOptions)
Window.scrollTo() scrolls to a particular set of
coordinates in the document.
[Value("scrollTo")]
public GlobalObject.Undefined ScrollTo(ScrollToOptions options = null)
Parameters
optionsScrollToOptions
Returns
Remarks
ScrollTo(double, double)
Window.scrollTo() scrolls to a particular set of
coordinates in the document.
[Value("scrollTo")]
public GlobalObject.Undefined ScrollTo(double x, double y)
Parameters
Returns
Remarks
ShowDirectoryPicker(DirectoryPickerOptions)
NOTE
ExperimentalshowDirectoryPicker() method of theWindow interface displays a directory picker which allows the user to
select a directory.
[Value("showDirectoryPicker")]
public Task<FileSystemDirectoryHandle> ShowDirectoryPicker(DirectoryPickerOptions options = null)
Parameters
optionsDirectoryPickerOptions
Returns
- Task<FileSystemDirectoryHandle>
A {{jsxref("Promise")}} whose fulfillment handler receives a 'FileSystemDirectoryHandle' object.
Remarks
ShowOpenFilePicker(OpenFilePickerOptions)
NOTE
ExperimentalshowOpenFilePicker() method of theWindow interface shows a file picker that allows a user to select a file
or multiple files and returns a handle for the file(s).
[Value("showOpenFilePicker")]
public Task<List<FileSystemFileHandle>> ShowOpenFilePicker(OpenFilePickerOptions options = null)
Parameters
optionsOpenFilePickerOptions
Returns
- Task<List<FileSystemFileHandle>>
A {{jsxref("Promise")}} whose fulfillment handler receives an {{jsxref('Array')}} of 'FileSystemFileHandle' objects.
Remarks
ShowSaveFilePicker(SaveFilePickerOptions)
NOTE
ExperimentalshowSaveFilePicker() method of theWindow interface shows a file picker that allows a user to save a file.
Either by selecting an existing file, or entering a name for a new file.
[Value("showSaveFilePicker")]
public Task<FileSystemFileHandle> ShowSaveFilePicker(SaveFilePickerOptions options = null)
Parameters
optionsSaveFilePickerOptions
Returns
- Task<FileSystemFileHandle>
A {{jsxref("Promise")}} whose fulfillment handler receives a 'FileSystemFileHandle' object.
Remarks
Stop()
The window.stop() stops further resource loading in the current
browsing context, equivalent to the stop button in the browser.
[Value("stop")]
public GlobalObject.Undefined Stop()
Returns
Remarks
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.