HTML Standard
source link: https://html.spec.whatwg.org/multipage/window-object.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Living Standard — Last Updated 19 February 2021
← 7 Loading web pages — Table of Contents — 7.5 Origin →7.3 The Window
object
[Global=Window,
Exposed=Window,
LegacyUnenumerableNamedProperties]
interfaceWindow : EventTarget {
// the current browsing context
[LegacyUnforgeable] readonlyattributeWindowProxy window;
[Replaceable] readonlyattributeWindowProxy self;
[LegacyUnforgeable] readonlyattributeDocument document;
attributeDOMStringname;
[PutForwards=href, LegacyUnforgeable] readonlyattributeLocation location;
readonlyattributeHistory history;
readonlyattributeCustomElementRegistry customElements;
[Replaceable] readonlyattributeBarProp locationbar;
[Replaceable] readonlyattributeBarProp menubar;
[Replaceable] readonlyattributeBarProp personalbar;
[Replaceable] readonlyattributeBarProp scrollbars;
[Replaceable] readonlyattributeBarProp statusbar;
[Replaceable] readonlyattributeBarProp toolbar;
attributeDOMStringstatus;
undefinedclose();
readonlyattributebooleanclosed;
undefinedstop();
undefinedfocus();
undefinedblur();
// other browsing contexts
[Replaceable] readonlyattributeWindowProxy frames;
[Replaceable] readonlyattributeunsignedlonglength;
[LegacyUnforgeable] readonlyattributeWindowProxy? top;
attributeanyopener;
[Replaceable] readonlyattributeWindowProxy? parent;
readonlyattributeElement? frameElement;
WindowProxy? open(optionalUSVStringurl = "", optionalDOMStringtarget = "_blank", optional [LegacyNullToEmptyString] DOMStringfeatures = "");
getter object (DOMStringname);
// Since this is the global object, the IDL named getter adds a NamedPropertiesObject exotic
// object on the prototype chain. Indeed, this does not make the global object an exotic object.
// Indexed access is taken care of by the WindowProxy exotic object.
// the user agent
readonlyattributeNavigator navigator;
readonlyattributebooleanoriginAgentCluster;
// user prompts
undefinedalert();
undefinedalert(DOMStringmessage);
booleanconfirm(optionalDOMStringmessage = "");
DOMString? prompt(optionalDOMStringmessage = "", optionalDOMStringdefault = "");
undefinedprint();
undefinedpostMessage(anymessage, USVStringtargetOrigin, optionalsequence<object> transfer = []);
undefinedpostMessage(anymessage, optionalWindowPostMessageOptions options = {});
// also has obsolete members
};
Window includesGlobalEventHandlers;
Window includesWindowEventHandlers;
dictionaryWindowPostMessageOptions : PostMessageOptions {
USVStringtargetOrigin = "/";
};
window . window
window . frames
window . self
These attributes all return window.
window .document
Returns the Document
associated with window.
defaultView
Returns the Window
object of the active document.
The Window
object has an associated
Document
, which is a Document
object. It is set when the
Window
object is created, and only ever changed during navigation from the initial about:blank
Document
.
The Window
object's browsing
context is the Window
object's associated Document
's browsing context. It is either null or a
browsing context.
The window
, frames
, and self
attributes' getters must return this Window
object's relevant Realm.[[GlobalEnv]]'s
EnvironmentRecord's [[GlobalThisValue]].
The document
IDL attribute, on getting, must
return this Window
object's associated
Document
.
The Document
object associated with a Window
object can
change in exactly one case: when the navigate algorithm creates a new Document
object for the
first page loaded in a browsing context. In that specific case, the
Window
object of the original about:blank
page is reused and gets a new
Document
object.
The defaultView
attribute's getter, when invoked, must
run these steps:
If this
Document
object's browsing context is null, then return null.Return this
Document
object's browsing context'sWindowProxy
object.
For historical reasons, Window
objects must also have a writable, configurable,
non-enumerable property named HTMLDocument
whose value is the
Document
interface object.
7.3.1 APIs for creating and navigating browsing contexts by name
window = window . open
( [ url [, target [, features ] ] ] )
Opens a window to show url (defaults to about:blank
), and returns it.
The target argument gives the name of the new window. If a window exists with that
name already, it is reused. The features argument can be used to influence the
rendering of the new window.
name
[ = value ]
Returns the name of the window.
Can be set, to change the name.
window .close
()
Closes the window.
window .closed
Returns true if the window has been closed, false otherwise.
window .stop
()
Cancels the document load.
The window open steps, given a string url, a string target, and a string features, are as follows:
If the event loop's termination nesting level is nonzero, return null.
Let source browsing context be the entry global object's browsing context.
If target is the empty string, then set target to "
_blank
".Let tokenizedFeatures be the result of tokenizing features.
Let noopener and noreferrer be false.
-
If tokenizedFeatures["
noopener
"] exists, then: -
If tokenizedFeatures["
noreferrer
"] exists, then: If noreferrer is true, then set noopener to true.
-
Let target browsing context and windowType be the result of applying the rules for choosing a browsing context given target, source browsing context, and noopener.
If there is a user agent that supports control-clicking a link to open it in a new tab, and the user control-clicks on an element whose
onclick
handler uses thewindow.open()
API to open a page in aniframe
element, the user agent could override the selection of the target browsing context to instead target a new tab. Let new be true if windowType is either "
new and unrestricted
" or "new with no opener
", and false otherwise.If target browsing context is null, then return null.
If new is true, then set up browsing context features for target browsing context given tokenizedFeatures. [CSSOMVIEW]
Let urlRecord be the URL "
about:blank
".-
If url is not the empty string or new is true, then:
If url is not the empty string, then parse url relative to the entry settings object, and set urlRecord to the resulting URL record, if any. If the parse a URL algorithm failed, then throw a "
SyntaxError
"DOMException
.If noreferrer is true, then set request's referrer to "
noreferrer
".Let window be target browsing context's active window.
If urlRecord is "
about:blank
" and new is true, then queue a global task on the networking task source given window to fire an event namedload
at window, with the legacy target override flag set.-
Otherwise:
Let historyHandling be "
replace
" if new is true; otherwise "default
".Navigate target browsing context to request, with exceptionsEnabled set to true, historyHandling set to historyHandling, and the source browsing context set to source browsing context.
If noopener is true or windowType is "
new with no opener
", then return null.-
Otherwise, if new is false, set target browsing context's opener browsing context to source browsing context.
If new is true this is done as part of creating a new auxiliary browsing context.
Return target browsing context's
WindowProxy
object.
The open(url, target,
features)
method on Window
objects provides a mechanism for
navigating an existing browsing context or opening and
navigating an auxiliary browsing context.
When the method is invoked, the user agent must run the window open steps with url, target, and features.
To tokenize the features argument:
Let tokenizedFeatures be a new ordered map.
Let position point at the first code point of features.
-
While position is not past the end of features:
Let name be the empty string.
Let value be the empty string.
Collect a sequence of code points that are feature separators from features given position. This skips past leading separators before the name.
Collect a sequence of code points that are not feature separators from features given position. Set name to the collected characters, converted to ASCII lowercase.
Set name to the result of normalizing the feature name name.
-
While position is not past the end of features and the code point at position in features is not U+003D (=):
If the code point at position in features is U+002C (,), or if it is not a feature separator, then break.
Advance position by 1.
This skips to the first U+003D (=) but does not skip past a U+002C (,) or a non-separator.
-
If the code point at position in features is a feature separator:
-
While position is not past the end of features and the code point at position in features is a feature separator:
If the code point at position in features is U+002C (,), then break.
Advance position by 1.
This skips to the first non-separator but does not skip past a U+002C (,).
Collect a sequence of code points that are not feature separators code points from features given position. Set value to the collected code points, converted to ASCII lowercase.
-
If name is not the empty string, then set tokenizedFeatures[name] to value.
Return tokenizedFeatures.
A code point is a feature separator if it is ASCII whitespace, U+003D (=), or U+002C (,).
For legacy reasons, there are some aliases of some feature names. To normalize a feature name name, switch on name:
"screenx
"
Return "left
".
"screeny
"
Return "top
".
"innerwidth
"
Return "width
".
"innerheight
"
Return "height
".
Anything else
Return name.
To parse a boolean feature given a string value:
If value is the empty string, then return true.
If value is "
yes
", then return true.Let parsed be the result of parsing value as an integer.
If parsed is an error, then set it to 0.
Return false if parsed is 0, and true otherwise.
The name
attribute's getter
must run these steps:
If this
Window
object's browsing context is null, then return the empty string.Return this
Window
object's browsing context's name.
The name
attribute's setter must run these steps:
If this
Window
object's browsing context is null, then return.Set this
Window
object's browsing context's name to the given value.
The name gets reset when the browsing context is navigated to another origin.
The close()
method must
run these steps:
A browsing context is script-closable if it is an auxiliary
browsing context that was created by a script (as opposed to by an action of the user), or
if it is a top-level browsing context whose session history contains
only one Document
.
The closed
attribute's getter must return true if this Window
object's browsing context is null or its is closing is true, and false
otherwise.
The stop()
method must
stop document loading given this Window
object's associated Document
.
7.3.2 Accessing other browsing contexts
window . length
Returns the number of document-tree child browsing contexts.
window[index]Returns the indicated document-tree child browsing context.
The number of document-tree child browsing
contexts of a Window
object W is the result of running these
steps:
The length
IDL attribute's
getter must return the number of document-tree child browsing contexts of this
Window
object.
Indexed access to document-tree child browsing contexts is defined through the [[GetOwnProperty]] internal method of the
WindowProxy
object.
7.3.3 Named access on the Window
object
window[name]
Returns the indicated element or collection of elements.
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to
this API can vary over time, as new features are added to the web platform, for example. Instead
of this, use document.getElementById()
or document.querySelector()
.
The document-tree child browsing context
name property set of a Window
object window is the return value of
running these steps:
If window's browsing context is null, then return the empty list.
Let childBrowsingContexts be all document-tree child browsing contexts of window's browsing context whose browsing context name is not the empty string, in order, and including only the first document-tree child browsing context with a given name if multiple document-tree child browsing contexts have the same one.
Remove each browsing context from childBrowsingContexts whose active document's origin is not same origin with window's relevant settings object's origin and whose browsing context name does not match the name of its container's
name
content attribute value.Return the browsing context names of childBrowsingContexts, in the same order.
This means that in the following example, hosted on https://example.org/
, assuming https://elsewhere.example/
sets window.name
to "spices
", evaluating
window.spices
after everything has loaded will yield undefined:
<iframesrc=https://elsewhere.example.com/></iframe><iframename=spices></iframe>
The Window
object supports named
properties. The supported property names of a Window
object
window at any moment consist of the following, in tree order according to
the element that contributed them, ignoring later duplicates:
window's document-tree child browsing context name property set;
the value of the
name
content attribute for allembed
,form
,img
, andobject
elements that have a non-emptyname
content attribute and are in a document tree with window's associatedDocument
as their root; andthe value of the
id
content attribute for all HTML elements that have a non-emptyid
content attribute and are in a document tree with window's associatedDocument
as their root.
To determine the value of a named property
name in a Window
object window, the user agent must return the
value obtained using the following steps:
-
Let objects be the list of named objects of window with the name name.
There will be at least one such object, by definition.
If objects contains a browsing context, then return the
WindowProxy
object of the nested browsing context of the first browsing context container in tree order whose nested browsing context is in objects.-
Otherwise, if objects has only one element, return that element.
Otherwise return an
HTMLCollection
rooted at window's associatedDocument
, whose filter matches only named objects of window with the name name. (By definition, these will all be elements.)
Named objects of Window
object
window with the name name, for the purposes of the above algorithm, consist
of the following:
document-tree child browsing contexts of window's associated
Document
whose name is name;embed
,form
,img
, orobject
elements that have aname
content attribute whose value is name and are in a document tree with window's associatedDocument
as their root; andHTML elements that have an
id
content attribute whose value is name and are in a document tree with window's associatedDocument
as their root.
7.3.4 Discarding browsing contexts
To discard a
Document
document:
Set document's salvageable state to false.
Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.
Abort document.
Remove any tasks associated with document in any task source, without running those tasks.
Discard all the child browsing contexts of document.
For each session history entry entry whose document is equal to document, set entry's document to null.
Set document's browsing context to null.
Remove document from the owner set of each
WorkerGlobalScope
object whose set contains document.For each workletGlobalScope in document's worklet global scopes, terminate workletGlobalScope.
To discard a browsing context browsingContext, run these steps:
Discard all
Document
objects for all the entries in browsingContext's session history.If browsingContext is a top-level browsing context, then remove browsingContext.
User agents may discard top-level browsing contexts at any time (typically, in
response to user requests, e.g., when a user force-closes a window containing one or more top-level browsing contexts). Other browsing contexts must be discarded once their
WindowProxy
object is eligible for garbage collection, in addition to the other
places where this specification requires them to be discarded.
7.3.5 Closing browsing contexts
To close a browsing context browsingContext, run these steps:
Prompt to unload browsingContext's active document. If the user refused to allow the document to be unloaded, then return.
Unload browsingContext's active document.
Remove browsingContext from the user interface (e.g., close or hide its tab in a tabbed browser).
Discard browsingContext.
User agents should offer users the ability to arbitrarily close any top-level browsing context.
7.3.6 Browser interface elements
To allow web pages to integrate with web browsers, certain web browser interface elements are exposed in a limited way to scripts in web pages.
Each interface element is represented by a BarProp
object:
[Exposed=Window]
interfaceBarProp {
readonlyattributebooleanvisible;
};
window . locationbar
. visible
Returns true if the location bar is visible; otherwise, returns false.
window .menubar
. visible
Returns true if the menu bar is visible; otherwise, returns false.
window .personalbar
. visible
Returns true if the personal bar is visible; otherwise, returns false.
window .scrollbars
. visible
Returns true if the scrollbars are visible; otherwise, returns false.
window .statusbar
. visible
Returns true if the status bar is visible; otherwise, returns false.
window .toolbar
. visible
Returns true if the toolbar is visible; otherwise, returns false.
The visible attribute's getter must run these steps:
If this
BarProp
object's relevant global object's browsing context is null, then return false.If the user agent does not have a user interface element that the object represents, as described below, then return true.
Return true or a value determined by the user agent to most accurately represent the visibility state of the user interface element that the object represents, as described below.
The following BarProp
objects must exist for each Window
object:
The location bar BarProp
objectRepresents the user interface element that contains a control that displays the
URL of the active document, or some similar interface concept.The menu bar BarProp
objectRepresents the user interface element that contains a list of commands in menu form, or some
similar interface concept.The personal bar BarProp
objectRepresents the user interface element that contains links to the user's favorite pages, or
some similar interface concept.The scrollbar BarProp
objectRepresents the user interface element that contains a scrolling mechanism, or some similar
interface concept.The status bar BarProp
objectRepresents a user interface element found immediately below or after the document, as
appropriate for the user's media, which typically provides information about ongoing network
activity or information about elements that the user's pointing device is current indicating. If
the user agent has no such user interface element, then the object may act as if the
corresponding user interface element was absent (i.e. its visible
attribute may return false).The toolbar BarProp
objectRepresents the user interface element found immediately above or before the document, as
appropriate for the user's media, which typically provides session history traversal
controls (back and forward buttons, reload buttons, etc). If the user agent has no such user
interface element, then the object may act as if the corresponding user interface element was
absent (i.e. its visible
attribute may return
false).
The locationbar
attribute must return the location bar BarProp
object.
The menubar
attribute must return the menu bar BarProp
object.
The personalbar
attribute must return the personal bar BarProp
object.
The scrollbars
attribute must return the scrollbar BarProp
object.
The statusbar
attribute must return the status bar BarProp
object.
The toolbar
attribute must return the toolbar BarProp
object.
For historical reasons, the status
attribute on the Window
object must,
on getting, return the last string it was set to, and on setting, must set itself to the new
value. When the Window
object is created, the attribute must be set to the empty
string. It does not do anything else.
7.3.7 Script settings for Window
objects
To set up a window environment settings object, given a URL creationURL, a JavaScript execution context execution context, null or an environment reservedEnvironment, a URL topLevelCreationURL, and an origin topLevelOrigin, run these steps:
Let realm be the value of execution context's Realm component.
Let window be realm's global object.
-
Let settings object be a new environment settings object whose algorithms are defined as follows:
Return execution context.
The module mapReturn the module map of window's associated
The responsible documentDocument
.Return window's associated
The API URL character encodingDocument
.Return the current character encoding of window's associated
The API base URLDocument
.Return the current base URL of window's associated
The originDocument
.Return the origin of window's associated
The referrer policyDocument
.Let document be window's associated
Document
.While document is an
iframe
srcdoc
document and document's referrer policy is the empty string, set document to document's browsing context's container document.Return document's referrer policy.
Return window's associated
The cross-origin isolated capabilityDocument
's embedder policy.Return true if both of the following hold, and false otherwise:
-
If reservedEnvironment is non-null, then:
Set settings object's id to reservedEnvironment's id, target browsing context to reservedEnvironment's target browsing context, and active service worker to reservedEnvironment's active service worker.
-
Set reservedEnvironment's id to the empty string.
The identity of the reserved environment is considered to be fully transferred to the created environment settings object. The reserved environment is not searchable by the environment’s id from this point on.
Otherwise, set settings object's id to a new unique opaque string, settings object's target browsing context to null, and settings object's active service worker to null.
Set settings object's creation URL to creationURL, settings object's top-level creation URL to topLevelCreationURL, and settings object's top-level origin to topLevelOrigin.
Set realm's [[HostDefined]] field to settings object.
7.4 The WindowProxy
exotic object
A WindowProxy
is an exotic object that wraps a
Window
ordinary object, indirecting most operations through to the wrapped object.
Each browsing context has an associated WindowProxy
object. When the
browsing context is navigated, the Window
object wrapped by the browsing context's associated WindowProxy
object
is changed.
The WindowProxy
exotic object must use the ordinary internal methods except where
it is explicitly specified otherwise below.
There is no WindowProxy
interface object.
Every WindowProxy
object has a [[Window]] internal slot representing the wrapped Window
object.
Although WindowProxy
is named as a "proxy", it does not do
polymorphic dispatch on its target's internal methods as a real proxy would, due to a desire to
reuse machinery between WindowProxy
and Location
objects. As long as the
Window
object remains an ordinary object this is unobservable and can be implemented
either way.
7.4.1 [[GetPrototypeOf]] ( )
Let W be the value of the [[Window]] internal slot of this.
If ! IsPlatformObjectSameOrigin(W) is true, then return ! OrdinaryGetPrototypeOf(W).
Return null.
7.4.2 [[SetPrototypeOf]] ( V )
Return ! SetImmutablePrototype(this, V).
7.4.3 [[IsExtensible]] ( )
Return true.
7.4.4 [[PreventExtensions]] ( )
Return false.
7.4.5 [[GetOwnProperty]] ( P )
Let W be the value of the [[Window]] internal slot of this.
-
If P is an array index property name, then:
Let index be ! ToUint32(P).
Let maxProperties be the number of document-tree child browsing contexts of W.
Let value be undefined.
If maxProperties is greater than 0 and index is less than maxProperties, then set value to the
WindowProxy
object of the indexth document-tree child browsing context of W's browsing context, sorted in the order that their browsing context container elements were most recently inserted into W's associatedDocument
, theWindowProxy
object of the most recently inserted browsing context container's nested browsing context being last.-
If value is undefined, then:
Return PropertyDescriptor{ [[Value]]: value, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: true }.
-
If ! IsPlatformObjectSameOrigin(W) is true, then return ! OrdinaryGetOwnProperty(W, P).
This is a willful violation of the JavaScript specification's invariants of the essential internal methods to maintain compatibility with existing web content. See tc39/ecma262 issue #672 for more information. [JAVASCRIPT]
Let property be ! CrossOriginGetOwnPropertyHelper(W, P).
If property is not undefined, then return property.
-
If property is undefined and P is in W's document-tree child browsing context name property set, then:
Let value be the
WindowProxy
object of the named object of W with the name P.-
Return PropertyDescriptor{ [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }.
The reason the property descriptors are non-enumerable, despite this mismatching the same-origin behavior, is for compatibility with existing web content. See issue #3183 for details.
Return ? CrossOriginPropertyFallback(P).
7.4.6 [[DefineOwnProperty]] ( P, Desc )
Let W be the value of the [[Window]] internal slot of this.
-
If ! IsPlatformObjectSameOrigin(W) is true, then:
If P is an array index property name, return false.
-
Return ? OrdinaryDefineOwnProperty(W, P, Desc).
This is a willful violation of the JavaScript specification's invariants of the essential internal methods to maintain compatibility with existing web content. See tc39/ecma262 issue #672 for more information. [JAVASCRIPT]
Throw a "
SecurityError
"DOMException
.
7.4.7 [[Get]] ( P, Receiver )
this is passed rather than W as OrdinaryGet and CrossOriginGet will invoke the [[GetOwnProperty]] internal method.
7.4.8 [[Set]] ( P, V, Receiver )
this is passed rather than W as OrdinarySet and CrossOriginSet will invoke the [[GetOwnProperty]] internal method. OrdinarySet will also invoke the [[DefineOwnProperty]] internal method.
7.4.9 [[Delete]] ( P )
Let W be the value of the [[Window]] internal slot of this.
-
If ! IsPlatformObjectSameOrigin(W) is true, then:
-
If P is an array index property name, then:
Let desc be ! this.[[GetOwnProperty]](P).
If desc is undefined, then return true.
Return false.
Return ? OrdinaryDelete(W, P).
-
Throw a "
SecurityError
"DOMException
.
7.4.10 [[OwnPropertyKeys]] ( )
Let W be the value of the [[Window]] internal slot of this.
Let keys be a new empty List.
Let maxProperties be the number of document-tree child browsing contexts of W.
Let index be 0.
-
Repeat while index < maxProperties,
Add ! ToString(index) as the last element of keys.
Increment index by 1.
If ! IsPlatformObjectSameOrigin(W) is true, then return the concatenation of keys and ! OrdinaryOwnPropertyKeys(W).
Return the concatenation of keys and ! CrossOriginOwnPropertyKeys(W).
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK