1. 7.2 ナビゲーションおよびセッション履歴に関連するAPI
      1. 7.2.1 Security infrastructure for Window, WindowProxy, and Location objects
        1. 7.2.1.1 Integration with IDL
        2. 7.2.1.2 Shared internal slot: [[CrossOriginPropertyDescriptorMap]]
        3. 7.2.1.3 Shared abstract operations
          1. 7.2.1.3.1 CrossOriginProperties ( O )
          2. 7.2.1.3.2 CrossOriginPropertyFallback ( P )
          3. 7.2.1.3.3 IsPlatformObjectSameOrigin ( O )
          4. 7.2.1.3.4 CrossOriginGetOwnPropertyHelper ( O, P )
          5. 7.2.1.3.5 CrossOriginGet ( O, P, Receiver )
          6. 7.2.1.3.6 CrossOriginSet ( O, P, V, Receiver )
          7. 7.2.1.3.7 CrossOriginOwnPropertyKeys ( O )
      2. 7.2.2 Windowオブジェクト
        1. 7.2.2.1 ウィンドウの開閉
        2. 7.2.2.2 Windowオブジェクトのインデックス付きアクセス
        3. 7.2.2.3 Windowオブジェクトの名前付きアクセス
        4. 7.2.2.4 関連ウィンドウへのアクセス
        5. 7.2.2.5 歴史的なブラウザーインターフェイス要素API
        6. 7.2.2.6 Script settings for Window objects
      3. 7.2.3 WindowProxy外来オブジェクト
        1. 7.2.3.1 [[GetPrototypeOf]] ( )
        2. 7.2.3.2 [[SetPrototypeOf]] ( V )
        3. 7.2.3.3 [[IsExtensible]] ( )
        4. 7.2.3.4 [[PreventExtensions]] ( )
        5. 7.2.3.5 [[GetOwnProperty]] ( P )
        6. 7.2.3.6 [[DefineOwnProperty]] ( P, Desc )
        7. 7.2.3.7 [[Get]] ( P, Receiver )
        8. 7.2.3.8 [[Set]] ( P, V, Receiver )
        9. 7.2.3.9 [[Delete]] ( P )
        10. 7.2.3.10 [[OwnPropertyKeys]] ( )
      4. 7.2.4 Locationインターフェイス
        1. 7.2.4.1 [[GetPrototypeOf]] ( )
        2. 7.2.4.2 [[SetPrototypeOf]] ( V )
        3. 7.2.4.3 [[IsExtensible]] ( )
        4. 7.2.4.4 [[PreventExtensions]] ( )
        5. 7.2.4.5 [[GetOwnProperty]] ( P )
        6. 7.2.4.6 [[DefineOwnProperty]] ( P, Desc )
        7. 7.2.4.7 [[Get]] ( P, Receiver )
        8. 7.2.4.8 [[Set]] ( P, V, Receiver )
        9. 7.2.4.9 [[Delete]] ( P )
        10. 7.2.4.10 [[OwnPropertyKeys]] ( )
      5. 7.2.5 Historyインターフェイス
      6. 7.2.6 イベントインターフェイス
        1. 7.2.6.1 PopStateEventインターフェイス
        2. 7.2.6.2 HashChangeEventインターフェイス
        3. 7.2.6.3 PageTransitionEventインターフェイス
        4. 7.2.6.4 BeforeUnloadEventインターフェイス

7.2.1 Security infrastructure for Window, WindowProxy, and Location objects

Although typically objects cannot be accessed across origins, the web platform would not be true to itself if it did not have some legacy exceptions to that rule that the web depends upon.

This section uses the terminology and typographic conventions from the JavaScript specification. [JAVASCRIPT]

7.2.1.1 Integration with IDL

When perform a security check is invoked, with a platformObject, identifier, and type, run these steps:

  1. If platformObject is not a Window or Location object, then return.

  2. For each e of CrossOriginProperties(platformObject):

    1. If SameValue(e.[[Property]], identifier) is true, then:

      1. If type is "method" and e has neither [[NeedsGet]] nor [[NeedsSet]], then return.

      2. Otherwise, if type is "getter" and e.[[NeedsGet]] is true, then return.

      3. Otherwise, if type is "setter" and e.[[NeedsSet]] is true, then return.

  3. If IsPlatformObjectSameOrigin(platformObject) is false, then throw a "SecurityError" DOMException.

7.2.1.2 Shared internal slot: [[CrossOriginPropertyDescriptorMap]]

Window and Location objects both have a [[CrossOriginPropertyDescriptorMap]] internal slot, whose value is initially an empty map.

The [[CrossOriginPropertyDescriptorMap]] internal slot contains a map with entries whose keys are (currentGlobal, objectGlobal, propertyKey)-tuples and values are property descriptors, as a memoization of what is visible to scripts when currentGlobal inspects a Window or Location object from objectGlobal. It is filled lazily by CrossOriginGetOwnPropertyHelper, which consults it on future lookups.

User agents should allow a value held in the map to be garbage collected along with its corresponding key when nothing holds a reference to any part of the value. That is, as long as garbage collection is not observable.

For example, with const href = Object.getOwnPropertyDescriptor(crossOriginLocation, "href").set the value and its corresponding key in the map cannot be garbage collected as that would be observable.

User agents may have an optimization whereby they remove key-value pairs from the map when document.domain is set. This is not observable as document.domain cannot revisit an earlier value.

For example, setting document.domain to "example.com" on www.example.com means user agents can remove all key-value pairs from the map where part of the key is www.example.com, as that can never be part of the origin again and therefore the corresponding value could never be retrieved from the map.

7.2.1.3 Shared abstract operations
7.2.1.3.1 CrossOriginProperties ( O )
  1. Assert: O is a Location or Window object.

  2. If O is a Location object, then return « { [[Property]]: "href", [[NeedsGet]]: false, [[NeedsSet]]: true }, { [[Property]]: "replace" } ».

  3. Return « { [[Property]]: "window", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "self", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "location", [[NeedsGet]]: true, [[NeedsSet]]: true }, { [[Property]]: "close" }, { [[Property]]: "closed", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "focus" }, { [[Property]]: "blur" }, { [[Property]]: "frames", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "length", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "top", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "opener", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "parent", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "postMessage" } ».

This abstract operation does not return a Completion Record.

Indexed properties do not need to be safelisted in this algorithm, as they are handled directly by the WindowProxy object.

A JavaScript property name P is a cross-origin accessible window property name if it is "window", "self", "location", "close", "closed", "focus", "blur", "frames", "length", "top", "opener", "parent", "postMessage", or an array index property name.

7.2.1.3.2 CrossOriginPropertyFallback ( P )
  1. If P is "then", @@toStringTag, @@hasInstance, or @@isConcatSpreadable, then return PropertyDescriptor{ [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

  2. Throw a "SecurityError" DOMException.

7.2.1.3.3 IsPlatformObjectSameOrigin ( O )
  1. Return true if the current settings object's origin is same origin-domain with O's relevant settings object's origin, and false otherwise.

This abstract operation does not return a Completion Record.

Here the current settings object roughly corresponds to the "caller", because this check occurs before the execution context for the getter/setter/method in question makes its way onto the JavaScript execution context stack. For example, in the code w.document, this step is invoked before the document getter is reached as part of the [[Get]] algorithm for the WindowProxy w.

7.2.1.3.4 CrossOriginGetOwnPropertyHelper ( O, P )

If this abstract operation returns undefined and there is no custom behavior, the caller needs to throw a "SecurityError" DOMException. In practice this is handled by the caller calling CrossOriginPropertyFallback.

  1. Let crossOriginKey be a tuple consisting of the current settings object, O's relevant settings object, and P.

  2. For each e of CrossOriginProperties(O):

    1. If SameValue(e.[[Property]], P) is true, then:

      1. If the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O contains an entry whose key is crossOriginKey, then return that entry's value.

      2. Let originalDesc be OrdinaryGetOwnProperty(O, P).

      3. Let crossOriginDesc be undefined.

      4. If e.[[NeedsGet]] and e.[[NeedsSet]] are absent, then:

        1. Let value be originalDesc.[[Value]].

        2. If IsCallable(value) is true, then set value to an anonymous built-in function, created in the current realm, that performs the same steps as the IDL operation P on object O.

        3. Set crossOriginDesc to PropertyDescriptor{ [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }.

      5. Otherwise:

        1. Let crossOriginGet be undefined.

        2. If e.[[NeedsGet]] is true, then set crossOriginGet to an anonymous built-in function, created in the current realm, that performs the same steps as the getter of the IDL attribute P on object O.

        3. Let crossOriginSet be undefined.

        4. If e.[[NeedsSet]] is true, then set crossOriginSet to an anonymous built-in function, created in the current realm, that performs the same steps as the setter of the IDL attribute P on object O.

        5. Set crossOriginDesc to PropertyDescriptor{ [[Get]]: crossOriginGet, [[Set]]: crossOriginSet, [[Enumerable]]: false, [[Configurable]]: true }.

      6. Create an entry in the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O with key crossOriginKey and value crossOriginDesc.

      7. Return crossOriginDesc.

  3. Return undefined.

This abstract operation does not return a Completion Record.

The reason that the property descriptors produced here are configurable is to preserve the invariants of the essential internal methods required by the JavaScript specification. In particular, since the value of the property can change as a consequence of navigation, it is required that the property be configurable. (However, see tc39/ecma262 issue #672 and references to it elsewhere in this specification for cases where we are not able to preserve these invariants, for compatibility with existing web content.) [JAVASCRIPT]

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.

7.2.1.3.5 CrossOriginGet ( O, P, Receiver )
  1. Let desc be ? O.[[GetOwnProperty]](P).

  2. Assert: desc is not undefined.

  3. If IsDataDescriptor(desc) is true, then return desc.[[Value]].

  4. Assert: IsAccessorDescriptor(desc) is true.

  5. Let getter be desc.[[Get]].

  6. If getter is undefined, then throw a "SecurityError" DOMException.

  7. Return ? Call(getter, Receiver).

7.2.1.3.6 CrossOriginSet ( O, P, V, Receiver )
  1. Let desc be ? O.[[GetOwnProperty]](P).

  2. Assert: desc is not undefined.

  3. If desc.[[Set]] is present and its value is not undefined, then:

    1. Perform ? Call(setter, Receiver, «V»).

    2. Return true.

  4. Throw a "SecurityError" DOMException.

7.2.1.3.7 CrossOriginOwnPropertyKeys ( O )
  1. Let keys be a new empty List.

  2. For each e of CrossOriginProperties(O), append e.[[Property]] to keys.

  3. Return the concatenation of keys and « "then", @@toStringTag, @@hasInstance, @@isConcatSpreadable ».

This abstract operation does not return a Completion Record.

7.2.2 Windowオブジェクト

Window

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+
[Global=Window,
 Exposed=Window,
 LegacyUnenumerableNamedProperties]
interface Window : EventTarget {
  // the current browsing context
  [LegacyUnforgeable] readonly attribute WindowProxy window;
  [Replaceable] readonly attribute WindowProxy self;
  [LegacyUnforgeable] readonly attribute Document document;
  attribute DOMString name;
  [PutForwards=href, LegacyUnforgeable] readonly attribute Location location;
  readonly attribute History history;
  readonly attribute CustomElementRegistry customElements;
  [Replaceable] readonly attribute BarProp locationbar;
  [Replaceable] readonly attribute BarProp menubar;
  [Replaceable] readonly attribute BarProp personalbar;
  [Replaceable] readonly attribute BarProp scrollbars;
  [Replaceable] readonly attribute BarProp statusbar;
  [Replaceable] readonly attribute BarProp toolbar;
  attribute DOMString status;
  undefined close();
  readonly attribute boolean closed;
  undefined stop();
  undefined focus();
  undefined blur();

  // other browsing contexts
  [Replaceable] readonly attribute WindowProxy frames;
  [Replaceable] readonly attribute unsigned long length;
  [LegacyUnforgeable] readonly attribute WindowProxy?top;
  attribute any opener;
  [Replaceable] readonly attribute WindowProxy?parent;
  readonly attribute Element?frameElement;
  WindowProxy?open(optional USVString url = "", optional DOMString target = "_blank", optional [LegacyNullToEmptyString] DOMString features = "");
  getter object (DOMString name);
  // 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
  readonly attribute Navigator navigator;
  readonly attribute Navigator clientInformation; // legacy alias of .navigator
  readonly attribute boolean originAgentCluster;

  // user prompts
  undefined alert();
  undefined alert(DOMString message);
  boolean confirm(optional DOMString message = "");
  DOMString?prompt(optional DOMString message = "", optional DOMString default = "");
  undefined print();

  undefined postMessage(any message, USVString targetOrigin, optional sequence<object> transfer = []);
  undefined postMessage(any message, optional WindowPostMessageOptions options = {});

  // also has obsolete members
};
Window includes GlobalEventHandlers;
Window includes WindowEventHandlers;

dictionary WindowPostMessageOptions : StructuredSerializeOptions {
  USVString targetOrigin = "/";
};
window.window

Window/window

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
window.frames

Window/frames

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
window.self

Window/self

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

これらの属性はすべてwindowを返す。

window.document

Window/document

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

windowと関連するDocumentを返す。

document.defaultView

Document/defaultView

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

documentに関連付けられたWindowがある場合はそれを返し、そうでなければnullを返す。

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.

A Window's browsing context is its associated Document's browsing context. It is either null or a browsing context.

A Window's navigable is the navigable whose active document is the Window's associated Document's, or null if there is no such navigable.

The window, frames, and self getter steps are to return this's relevant realm.[[GlobalEnv]].[[GlobalThisValue]].

The document getter steps are to return this'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 initial about:blank page is reused and gets a new Document object.

The defaultView getter steps are:

  1. If this's browsing context is null, then return null.

  2. Return this's browsing context's WindowProxy object.


HTMLDocument

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

For historical reasons, Window objects must also have a writable, configurable, non-enumerable property named HTMLDocument whose value is the Document interface object.

7.2.2.1 ウィンドウの開閉
window = window.open([ url [, target [, features ] ] ])

Window/open

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

url(デフォルトで"about:blank")を表示するためのウィンドウを開き、それを返す。target(デフォルトで"_blank")は、新しいウィンドウの名前を示す。すでにその名前をもつウィンドウが存在する場合、それが再利用される。features引数はコンマ区切りトークンの集合を含むことができる:

"noopener"
"noreferrer"

これらは、ハイパーリンク上のnoopenerおよびnoreferrerリンクタイプと同等に動作する。

"popup"

ユーザーエージェントに、新しいウィンドウに最小限のウェブブラウザーユーザーインターフェイスを提供するように促す。 (すべてのBarPropオブジェクトにもvisibleゲッターに影響を与える。)

globalThis.open("https://email.example/message/CAOOOkFcWW97r8yg=SsWg7GgCmp4suVX9o85y8BvNRqMjuc5PXg", undefined, "noopener,popup");
window.name [ = value ]

Window/name

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

ウィンドウの名前を返す。

名前を変更する設定が可能である。

window.close()

Window/close

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

ウィンドウを閉じる。

window.closed

Window/closed

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

ウィンドウが閉じられている場合はtrueを返し、そうでなければfalseを返す。

window.stop()

Window/stop

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

ドキュメントの読み込みを中止する。

The window open steps, given a string url, a string target, and a string features, are as follows:

  1. If the event loop's termination nesting level is nonzero, return null.

  2. Let sourceDocument be the entry global object's associated Document.

  3. If target is the empty string, then set target to "_blank".

  4. Let tokenizedFeatures be the result of tokenizing features.

  5. Let noopener and noreferrer be false.

  6. If tokenizedFeatures["noopener"] exists, then:

    1. Set noopener to the result of parsing tokenizedFeatures["noopener"] as a boolean feature.

    2. Remove tokenizedFeatures["noopener"].

  7. If tokenizedFeatures["noreferrer"] exists, then:

    1. Set noreferrer to the result of parsing tokenizedFeatures["noreferrer"] as a boolean feature.

    2. Remove tokenizedFeatures["noreferrer"].

  8. Let referrerPolicy be the empty string.

  9. If noreferrer is true, then set noopener to true and set referrerPolicy to "no-referrer".

  10. Let targetNavigable and windowType be the result of applying the rules for choosing a navigable given target, sourceDocument's node navigable, 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 the window.open() API to open a page in an iframe element, the user agent could override the selection of the target browsing context to instead target a new tab.

  11. If targetNavigable is null, then return null.

  12. If windowType is either "new and unrestricted" or "new with no opener", then:

    1. Set targetNavigable's active browsing context's is popup to the result of checking if a popup window is requested, given tokenizedFeatures.

    2. Set up browsing context features for targetNavigable's active browsing context given tokenizedFeatures.[CSSOMVIEW]

    3. Let urlRecord be the URL record about:blank.

    4. 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.

    5. If urlRecord matches about:blank, then perform the URL and history update steps given targetNavigable's active document and urlRecord.

      This is necessary in case url is something like about:blank?foo. If url is just plain about:blank, this will do nothing.

    6. Otherwise, navigate targetNavigable to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.

  13. Otherwise:

    1. If url is not the empty string, then:

      1. Let urlRecord be the URL record about:blank.

      2. 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.

      3. Navigate targetNavigable to urlRecord using sourceDocument, with referrerPolicy set to referrerPolicy and exceptionsEnabled set to true.

    2. If noopener is false, then set targetNavigable's active browsing context's opener browsing context to sourceDocument's browsing context.

  14. If noopener is true or windowType is "new with no opener", then return null.

  15. Return targetNavigable's active WindowProxy.

The open(url, target, features) method steps are to run the window open steps with url, target, and features.

The method provides a mechanism for navigating an existing browsing context or opening and navigating an auxiliary browsing context.


To tokenize the features argument:

  1. Let tokenizedFeatures be a new ordered map.

  2. Let position point at the first code point of features.

  3. While position is not past the end of features:

    1. Let name be the empty string.

    2. Let value be the empty string.

    3. Collect a sequence of code points that are feature separators from features given position. This skips past leading separators before the name.

    4. 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.

    5. Set name to the result of normalizing the feature name name.

    6. While position is not past the end of features and the code point at position in features is not U+003D (=):

      1. If the code point at position in features is U+002C (,), or if it is not a feature separator, then break.

      2. Advance position by 1.

      This skips to the first U+003D (=) but does not skip past a U+002C (,) or a non-separator.

    7. If the code point at position in features is a feature separator:

      1. While position is not past the end of features and the code point at position in features is a feature separator:

        1. If the code point at position in features is U+002C (,), then break.

        2. Advance position by 1.

        This skips to the first non-separator but does not skip past a U+002C (,).

      2. 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.

    8. If name is not the empty string, then set tokenizedFeatures[name] to value.

  4. Return tokenizedFeatures.

To check if a window feature is set, given tokenizedFeatures, featureName, and defaultValue:

  1. If tokenizedFeatures[featureName] exists, then return the result of parsing tokenizedFeatures[featureName] as a boolean feature.

  2. Return defaultValue.

To check if a popup window is requested, given tokenizedFeatures:

  1. If tokenizedFeatures is empty, then return false.

  2. If tokenizedFeatures["popup"] exists, then return the result of parsing tokenizedFeatures["popup"] as a boolean feature.

  3. Let location be the result of checking if a window feature is set, given tokenizedFeatures, "location", and false.

  4. Let toolbar be the result of checking if a window feature is set, given tokenizedFeatures, "toolbar", and false.

  5. If location and toolbar are both false, then return true.

  6. Let menubar be the result of checking if a window feature is set, given tokenizedFeatures, menubar", and false.

  7. If menubar is false, then return true.

  8. Let resizable be the result of checking if a window feature is set, given tokenizedFeatures, "resizable", and true.

  9. If resizable is false, then return true.

  10. Let scrollbars be the result of checking if a window feature is set, given tokenizedFeatures, "scrollbars", and false.

  11. If scrollbars is false, then return true.

  12. Let status be the result of checking if a window feature is set, given tokenizedFeatures, "status", and false.

  13. If status is false, then return true.

  14. falseを返す。

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:

  1. If value is the empty string, then return true.

  2. If value is "yes", then return true.

  3. If value is "true", then return true.

  4. Let parsed be the result of parsing value as an integer.

  5. If parsed is an error, then set it to 0.

  6. Return false if parsed is 0, and true otherwise.


The name getter steps are:

  1. If this's navigable is null, then return the empty string.

  2. Return this's navigable's target name.

The name setter steps are:

  1. If this's navigable is null, then return.

  2. Set this's navigable's active session history entry's document state's navigable target name to the given value.

The name gets reset when the navigable is navigated to another origin.


The close() method steps are:

  1. Let thisTraversable be null.

  2. For each top-level traversable traversable of the user agent's top-level traversable set: if traversable's active document's relevant global object equals this, then set thisTraversable to traversable and break.

  3. If thisTraversable is null, then return.

    In this case the method is being called on a Window that does not correspond to a top-level traversable, and so closing is not allowed.

  4. If thisTraversable's is closing is true, then return.

  5. Let browsingContext be thisTraversable's active browsing context.

  6. Let sourceSnapshotParams be the result of snapshotting source snapshot params given thisTraversable's active document.

  7. If all the following are true:

    then:

    1. Set thisTraversable's is closing to true.

    2. Queue a task on the DOM manipulation task source to close thisTraversable.

A navigable is script-closable if its active browsing context 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 traversable whose session history entries's size is 1.

The closed getter steps are to return true if this's browsing context is null or its is closing is true; otherwise false.

The stop() method steps are:

  1. If this's navigable is null, then return.

  2. Stop loading this's navigable.

7.2.2.2 Windowオブジェクトのインデックス付きアクセス
window.length

Window/length

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

文書ツリーの子ナビゲート可能の数を返す。

window[index]

指定された文書ツリーの子ナビゲート可能に対応するWindowProxyを返す。

The length getter steps are to return this's associated Document's document-tree child navigables's size.

Indexed access to document-tree child navigables is defined through the [[GetOwnProperty]] internal method of the WindowProxy object.

7.2.2.3 Windowオブジェクトの名前付きアクセス
window[name]

指示された要素または要素のコレクションを返す。

一般的な規則として、これに依存することはもろいコードを導く。たとえば、新しい機能がウェブプラットフォームに加えられるように、いずれかのIDがこのAPIのマッピングで終わることは時間をかけて変化できる。この代わりに、document.getElementById()またはdocument.querySelector()を使用する。

The document-tree child navigable target name property set of a Window object window is the return value of running these steps:

  1. Let children be the document-tree child navigables of window's associated Document.

  2. Let firstNamedChildren be an empty ordered set.

  3. For each navigable of children:

    1. Let name be navigable's target name.

    2. If name is the empty string, then continue.

    3. If firstNamedChildren contains a navigable whose target name is name, then continue.

    4. Append navigable to firstNamedChildren.

  4. Let names be an empty ordered set.

  5. For each navigable of firstNamedChildren:

    1. Let name be navigable's target name.

    2. If navigable's active document's origin is same origin with window's relevant settings object's origin, then append name to names.

  6. Return names.

The two seperate iterations mean 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:

<iframe src=https://elsewhere.example.com/></iframe>
<iframe name=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:

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:

  1. Let objects be the list of named objects of window with the name name.

    There will be at least one such object, by definition.

  2. If objects contains a navigable, then:

    1. Let container be the first navigable container in window's associated Document's descendants whose content navigable is in objects.

    2. Return container's content navigable's active WindowProxy.

  3. Otherwise, if objects has only one element, return that element.

  4. Otherwise return an HTMLCollection rooted at window's associated Document, 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:

window.top

Window/top

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

トップレベルトラバーサルWindowProxyを返す。

window.opener [ = value ]

Window/opener

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

オープナーブラウジングコンテキストに対するWindowProxyを返す。

存在しないまたはnullが設定されている場合、nullを返す。

nullに設定可能である。

window.parent

Window/parent

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

親ナビゲート可能に対するWindowProxyを返す。

window.frameElement

Window/frameElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

ナビゲート可能コンテナー要素を返す。

存在しない場合、生成元をまたいだ状況でnullを返す。

The top getter steps are:

  1. If this's navigable is null, then return null.

  2. Return this's navigable's top-level traversable's active WindowProxy.

The opener getter steps are:

  1. Let current be this's browsing context.

  2. If current is null, then return null.

  3. If current's opener browsing context is null, then return null.

  4. Return current's opener browsing context's WindowProxy object.

The opener setter steps are:

  1. If the given value is null and this's browsing context is non-null, then set this's browsing context's opener browsing context to null.

  2. If the given value is non-null, then return ? OrdinaryDefineOwnProperty(this, "opener", { [[Value]]: the given value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }).

Setting window.opener to null clears the opener browsing context reference. In practice, this prevents future scripts from accessing their opener browsing context's Window object.

By default, scripts can access their opener browsing context's Window object through the window.opener getter. E.g., a script can set window.opener.location, causing the opener browsing context to navigate.

The parent getter steps are:

  1. Let navigable be this's navigable.

  2. If navigable is null, then return null.

  3. If navigable's parent is not null, then set navigable to navigable's parent.

  4. Return navigable's active WindowProxy.

The frameElement getter steps are:

  1. Let current be this's node navigable.

  2. If current is null, then return null.

  3. Let container be current's container.

  4. If container is null, then return null.

  5. If container's node document's origin is not same origin-domain with the current settings object's origin, then return null.

  6. Return container.

An example of when these properties can return null is as follows:

<!DOCTYPE html>
<iframe></iframe>

<script>
"use strict";
const element = document.querySelector("iframe");
const iframeWindow = element.contentWindow;
element.remove();

console.assert(iframeWindow.top === null);
console.assert(iframeWindow.parent === null);
console.assert(iframeWindow.frameElement === null);
</script>

Here the browsing context corresponding to iframeWindow was nulled out when element was removed from the document.

7.2.2.5 歴史的なブラウザーインターフェイス要素API

歴史的な理由から、Windowインターフェイスには、特定のウェブブラウザーインターフェイス要素の可視性を表すいくつかのプロパティがあった。

プライバシーと相互運用性の理由から、これらのプロパティは、Windowブラウジングコンテキストポップアッププロパティがtrueかfalseかを表す値を返すようになった。

各インターフェイス要素はBarPropオブジェクトによって表される:

BarProp

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
[Exposed=Window]
interface BarProp {
  readonly attribute boolean visible;
};
window.locationbar.visible

Window/locationbar

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android?
window.menubar.visible

Window/menubar

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android?
window.personalbar.visible

Window/personalbar

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
window.scrollbars.visible

Window/scrollbars

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
window.statusbar.visible

Window/statusbar

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android?
window.toolbar.visible

Window/toolbar

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android?

Windowがポップアップでない場合はtrueを返す。そうでなければfalseを返す。

BarProp/visible

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera?Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS1+Chrome Android?WebView Android37+Samsung Internet?Opera Android?

The visible getter steps are:

  1. Let browsingContext be this's relevant global object's browsing context.

  2. If browsingContext is null, then return true.

  3. Return the negation of browsingContext's top-level browsing context's is popup.

The following BarProp objects must exist for each Window object:

The location bar BarProp object
Historically represented the user interface element that contains a control that displays the browser's location bar.
The menu bar BarProp object
Historically represented the user interface element that contains a list of commands in menu form, or some similar interface concept.
The personal bar BarProp object
Historically represented the user interface element that contains links to the user's favorite pages, or some similar interface concept.
The scrollbar BarProp object
Historically represented the user interface element that contains a scrolling mechanism, or some similar interface concept.
The status bar BarProp object
Historically represented 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 currently indicating.
The toolbar BarProp object
Historically represented 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.).

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.2.2.6 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:

  1. Let realm be the value of execution context's Realm component.

  2. Let window be realm's global object.

  3. Let settings object be a new environment settings object whose algorithms are defined as follows:

    The realm execution context

    Return execution context.

    The module map

    Return the module map of window's associated Document.

    The API URL character encoding

    Return the current character encoding of window's associated Document.

    The API base URL

    Return the current base URL of window's associated Document.

    The origin

    Return the origin of window's associated Document.

    The policy container

    Return the policy container of window's associated Document.

    The cross-origin isolated capability

    Return true if both of the following hold, and false otherwise:

    1. realm's agent cluster's cross-origin-isolation mode is "concrete", and

    2. window's associated Document is allowed to use the "cross-origin-isolated" feature.

    The time origin

    Return window's associated Document's load timing info's navigation start time.

  4. If reservedEnvironment is non-null, then:

    1. 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.

    2. 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.

  5. 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.

  6. 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.

  7. Set realm's [[HostDefined]] field to settings object.

7.2.3 WindowProxy外来オブジェクト

WindowProxyは、Windowの通常のオブジェクトをラップする外来オブジェクトであり、ほとんどの操作をラップされたオブジェクトに間接的に転送する。各ブラウジングコンテキストは、関連するWindowProxyオブジェクトを持つ。ブラウジングコンテキストナビゲートされるとき、ブラウジングコンテキストの関連付けられ WindowProxyオブジェクトによってラップされたWindowオブジェクトが変更される。

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.2.3.1 [[GetPrototypeOf]] ( )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. If IsPlatformObjectSameOrigin(W) is true, then return ! OrdinaryGetPrototypeOf(W).

  3. Return null.

7.2.3.2 [[SetPrototypeOf]] ( V )
  1. Return ! SetImmutablePrototype(this, V).

7.2.3.3 [[IsExtensible]] ( )
  1. Return true.

7.2.3.4 [[PreventExtensions]] ( )
  1. falseを返す。

7.2.3.5 [[GetOwnProperty]] ( P )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. If P is an array index property name, then:

    1. Let index be ! ToUint32(P).

    2. Let children be the document-tree child navigables of W's associated Document.

    3. Let value be undefined.

    4. If index is less than children's size, then:

      1. Sort children in ascending order, with navigableA being less than navigableB if navigableA's container was inserted into W's associated Document earlier than navigableB's container was.

      2. Set value to children[index]'s active WindowProxy.

    5. If value is undefined, then:

      1. If IsPlatformObjectSameOrigin(W) is true, then return undefined.

      2. Throw a "SecurityError" DOMException.

    6. Return PropertyDescriptor{ [[Value]]: value, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: true }.

  3. 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]

  4. Let property be CrossOriginGetOwnPropertyHelper(W, P).

  5. If property is not undefined, then return property.

  6. If property is undefined and P is in W's document-tree child navigable target name property set, then:

    1. Let value be the active WindowProxy of the named object of W with the name P.

    2. 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.

  7. Return ? CrossOriginPropertyFallback(P).

7.2.3.6 [[DefineOwnProperty]] ( P, Desc )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. If IsPlatformObjectSameOrigin(W) is true, then:

    1. If P is an array index property name, return false.

    2. 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]

  3. Throw a "SecurityError" DOMException.

7.2.3.7 [[Get]] ( P, Receiver )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. Check if an access between two browsing contexts should be reported, given the current global object's browsing context, W's browsing context, P, and the current settings object.

  3. If IsPlatformObjectSameOrigin(W) is true, then return ? OrdinaryGet(this, P, Receiver).

  4. Return ? CrossOriginGet(this, P, Receiver).

this is passed rather than W as OrdinaryGet and CrossOriginGet will invoke the [[GetOwnProperty]] internal method.

7.2.3.8 [[Set]] ( P, V, Receiver )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. Check if an access between two browsing contexts should be reported, given the current global object's browsing context, W's browsing context, P, and the current settings object.

  3. If IsPlatformObjectSameOrigin(W) is true, then:

    1. If P is an array index property name, then return false.

    2. Return ? OrdinarySet(W, P, V, Receiver).

  4. Return ? CrossOriginSet(this, P, V, Receiver).

    this is passed rather than W as CrossOriginSet will invoke the [[GetOwnProperty]] internal method.

7.2.3.9 [[Delete]] ( P )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. If IsPlatformObjectSameOrigin(W) is true, then:

    1. If P is an array index property name, then:

      1. Let desc be ! this.[[GetOwnProperty]](P).

      2. If desc is undefined, then return true.

      3. falseを返す。

    2. Return ? OrdinaryDelete(W, P).

  3. Throw a "SecurityError" DOMException.

7.2.3.10 [[OwnPropertyKeys]] ( )
  1. Let W be the value of the [[Window]] internal slot of this.

  2. Let maxProperties be W's associated Document's document-tree child navigables's size.

  3. Let keys be the range 0 to maxProperties, exclusive.

  4. If IsPlatformObjectSameOrigin(W) is true, then return the concatenation of keys and OrdinaryOwnPropertyKeys(W).

  5. Return the concatenation of keys and ! CrossOriginOwnPropertyKeys(W).

7.2.4 Locationインターフェイス

Document/location

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Location

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet?Opera Android10.1+

Window/location

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Windowオブジェクトは、Locationオブジェクトの一意なインスタンスに関連付けられており、Windowオブジェクトの作成時に割り当てられる。

The Location exotic object is defined through a mishmash of IDL, invocation of JavaScript internal methods post-creation, and overridden JavaScript internal methods. Coupled with its scary security policy, please take extra care while implementing this excrescence.

To create a Location object, run these steps:

  1. Let location be a new Location platform object.

  2. Let valueOf be location's relevant realm.[[Intrinsics]].[[%Object.prototype.valueOf%]].

  3. Perform ! location.[[DefineOwnProperty]]("valueOf", { [[Value]]: valueOf, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).

  4. Perform ! location.[[DefineOwnProperty]](@@toPrimitive, { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).

  5. Set the value of the [[DefaultProperties]] internal slot of location to location.[[OwnPropertyKeys]]().

  6. Return location.

The addition of valueOf and @@toPrimitive own data properties, as well as the fact that all of Location's IDL attributes are marked [LegacyUnforgeable], is required by legacy code that consulted the Location interface, or stringified it, to determine the document URL, and then used it in a security-sensitive way. In particular, the valueOf, @@toPrimitive, and [LegacyUnforgeable] stringifier mitigations ensure that code such as foo[location] = bar or location + "" cannot be misdirected.

document.location [ = value ]
window.location [ = value ]

現在のページの位置とLocationオブジェクトを返す。

別のページにナビゲートするために、設定可能である。

The Document object's location getter steps are to return this's relevant global object's Location object, if this is fully active, and null otherwise.

The Window object's location getter steps are to return this's Location object.

Location objects provide a representation of the URL of their associated Document, as well as methods for navigating and reloading the associated navigable.

[Exposed=Window]
interface Location { // but see also additional creation steps and overridden internal methods
  [LegacyUnforgeable] stringifier attribute USVString href;
  [LegacyUnforgeable] readonly attribute USVString origin;
  [LegacyUnforgeable] attribute USVString protocol;
  [LegacyUnforgeable] attribute USVString host;
  [LegacyUnforgeable] attribute USVString hostname;
  [LegacyUnforgeable] attribute USVString port;
  [LegacyUnforgeable] attribute USVString pathname;
  [LegacyUnforgeable] attribute USVString search;
  [LegacyUnforgeable] attribute USVString hash;

  [LegacyUnforgeable] undefined assign(USVString url);
  [LegacyUnforgeable] undefined replace(USVString url);
  [LegacyUnforgeable] undefined reload();

  [LegacyUnforgeable, SameObject] readonly attribute DOMStringList ancestorOrigins;
};
location.toString()
location.href

Location/href

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Location/toString

Support in all current engines.

Firefox22+Safari1+Chrome52+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

LocationオブジェクトのURLを返す。

与えられたURLにナビゲートするように、設定可能である。

location.origin

Location/origin

Support in all current engines.

Firefox21+Safari5.1+Chrome8+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS?Chrome Android?WebView Android3+Samsung Internet?Opera Android?

Locationオブジェクトの生成元を返す。

location.protocol

Location/protocol

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Locationオブジェクトのスキームを返す。

変更されたスキームと同じURLにナビゲートするように、設定可能である。

location.host

Location/host

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

LocationオブジェクトのURLのホストとポートを返す(スキームのデフォルトポートと異なる場合)。

変更されたホストおよびポートと同じURLにナビゲートするように、設定可能である。

location.hostname

Location/hostname

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Locationオブジェクトのホストを返す。

変更されたホストと同じURLにナビゲートするように、設定可能である。

location.port

Location/port

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Locationオブジェクトのポートを返す。

変更されたポートと同じURLにナビゲートするように、設定可能である。

location.pathname

Location/pathname

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

Locationオブジェクトのパスを返す。

変更されたパスと同じURLにナビゲートするように、設定可能である。

location.search

Location/search

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

LocationオブジェクトのURLのクエリーを返す(空でない場合は先頭の"?"を含む)。

(先頭の"?"を無視して)変更されたクエリーと同じURLにナビゲートするように、設定可能である。

location.hash

Location/hash

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

LocationオブジェクトのURLのフラグメントを返す(空でない場合は先頭の"#"を含む)。

(先頭の"#"を無視して)変更されたフラグメントと同じURLにナビゲートするように、設定可能である。

location.assign(url)

Location/assign

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS1+Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

与えられたURLにナビゲートする。

location.replace(url)

Location/replace

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

セッション履歴から現在のページを削除し、与えられたURLにナビゲートする。

location.reload()

Location/reload

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

現在のページをリロードする。

location.ancestorOrigins

Location/ancestorOrigins

FirefoxNoSafari6+Chrome20+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

祖先ナビゲート可能アクティブな文書の生成元を列挙する DOMStringListオブジェクトを返す。

A Location object has an associated relevant Document, which is its relevant global object's browsing context's active document, if this Location object's relevant global object's browsing context is non-null, and null otherwise.

A Location object has an associated url, which is this Location object's relevant Document's URL, if this Location object's relevant Document is non-null, and about:blank otherwise.

A Location object has an associated ancestor origins list. When a Location object is created, its ancestor origins list must be set to a DOMStringList object whose associated list is the list of strings that the following steps would produce:

  1. Let output be a new list of strings.

  2. Let current be the Location object's relevant Document.

  3. While current's container document is non-null:

    1. Set current to current's container document.

    2. Append the serialization of current's origin to output.

  4. Return output.

To Location-object navigate a Location object location to a URL url, optionally given a history handling behavior historyHandling (default "push"):

  1. Let navigable be location's relevant global object's navigable.

  2. Let sourceDocument be the incumbent global object's associated Document.

  3. If location's relevant Document is not yet completely loaded, and the incumbent global object does not have transient activation, then set historyHandling to "replace".

  4. Navigate navigable to url using sourceDocument, with exceptionsEnabled set to true and historyHandling set to historyHandling.

The href getter steps are:

  1. If this's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. Return this's url, serialized.

The href setter steps are:

  1. If this's relevant Document is null, then return.

  2. Parse the given value relative to the entry settings object. If that failed, throw a "SyntaxError" DOMException.

  3. Location-object navigate this to the resulting URL record.

The href setter intentionally has no security check.

The origin getter steps are:

  1. If this's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. Return the serialization of this's url's origin.

The protocol getter steps are:

  1. If this's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. Return this's url's scheme, followed by ":".

The protocol setter steps are:

  1. If this's relevant Document is null, then return.

  2. If this's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this's url.

  4. Let possibleFailure be the result of basic URL parsing the given value, followed by ":", with copyURL as url and scheme start state as state override.

    Because the URL parser ignores multiple consecutive colons, providing a value of "https:" (or even "https::::") is the same as providing a value of "https".

  5. If possibleFailure is failure, then throw a "SyntaxError" DOMException.

  6. If copyURL's scheme is not an HTTP(S) scheme, then terminate these steps.

  7. Location-object navigate this to copyURL.

The host getter steps are:

  1. If this's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. Let url be this's url.

  3. If url's host is null, return the empty string.

  4. If url's port is null, return url's host, serialized.

  5. Return url's host, serialized, followed by ":" and url's port, serialized.

The host setter steps are:

  1. If this's relevant Document is null, then return.

  2. If this's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this's url.

  4. If copyURL has an opaque path, then return.

  5. Basic URL parse the given value, with copyURL as url and host state as state override.

  6. Location-object navigate this to copyURL.

The hostname getter steps are:

  1. If this's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. If this's url's host is null, return the empty string.

  3. Return this's url's host, serialized.

The hostname setter steps are:

  1. If this's relevant Document is null, then return.

  2. If this's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this's url.

  4. If copyURL has an opaque path, then return.

  5. Basic URL parse the given value, with copyURL as url and hostname state as state override.

  6. Location-object navigate this to copyURL.

The port getter steps are:

  1. If this's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. If this's url's port is null, return the empty string.

  3. Return this's url's port, serialized.

The port setter steps are:

  1. If this's relevant Document is null, then return.

  2. If this's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this's url.

  4. If copyURL cannot have a username/password/port, then return.

  5. If the given value is the empty string, then set copyURL's port to null.

  6. Otherwise, basic URL parse the given value, with copyURL as url and port state as state override.

  7. Location-object navigate this to copyURL.

The pathname getter steps are:

  1. If this's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. Return the result of URL path serializing this Location object's url.

The pathname setter steps are:

  1. If this's relevant Document is null, then return.

  2. If this's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this's url.

  4. If copyURL has an opaque path, then return.

  5. Set copyURL's path to the empty list.

  6. Basic URL parse the given value, with copyURL as url and path start state as state override.

  7. Location-object navigate this to copyURL.

The search getter steps are:

  1. If this's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. If this's url's query is either null or the empty string, return the empty string.

  3. Return "?", followed by this's url's query.

The search setter steps are:

  1. If this's relevant Document is null, then return.

  2. If this's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this's url.

  4. If the given value is the empty string, set copyURL's query to null.

  5. そうでなければ、以下のサブ手順を実行する:

    1. Let input be the given value with a single leading "?" removed, if any.

    2. Set copyURL's query to the empty string.

    3. Basic URL parse input, with null, the relevant Document's document's character encoding, copyURL as url, and query state as state override.

  6. Location-object navigate this to copyURL.

The hash getter steps are:

  1. If this's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. If this's url's fragment is either null or the empty string, return the empty string.

  3. Return "#", followed by this's url's fragment.

The hash setter steps are:

  1. If this's relevant Document is null, then return.

  2. If this's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this's url.

  4. Let input be the given value with a single leading "#" removed, if any.

  5. Set copyURL's fragment to the empty string.

  6. Basic URL parse input, with copyURL as url and fragment state as state override.

  7. If copyURL's fragment is this's url's fragment, then return.

    This bailout is necessary for compatibility with deployed content, which redundantly sets location.hash on scroll. It does not apply to other mechanisms of fragment navigation, such as the location.href setter or location.assign().

  8. Location-object navigate this to copyURL.

Unlike the equivalent API for the a and area elements, the hash setter does not special case the empty string, to remain compatible with deployed scripts.


The assign(url) method steps are:

  1. If this's relevant Document is null, then return.

  2. If this's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Parse url relative to the entry settings object. If that failed, throw a "SyntaxError" DOMException.

  4. Location-object navigate this to the resulting URL record.

The replace(url) method steps are:

  1. If this's relevant Document is null, then return.

  2. Parse url relative to the entry settings object. If that failed, throw a "SyntaxError" DOMException.

  3. Location-object navigate this to the resulting URL record given "replace".

The replace() method intentionally has no security check.

The reload() method steps are:

  1. Let document be this's relevant Document.

  2. If document is null, then return.

  3. If document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  4. Reload document's node navigable.


The ancestorOrigins getter steps are:

  1. If this's relevant Document is null, then return an empty list.

  2. If this's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Otherwise, return this's ancestor origins list.

The details of how the ancestorOrigins attribute works are still controversial and might change. See issue #1918 for more information.


As explained earlier, the Location exotic object requires additional logic beyond IDL for security purposes. The Location object must use the ordinary internal methods except where it is explicitly specified otherwise below.

Also, every Location object has a [[DefaultProperties]] internal slot representing its own properties at time of its creation.

7.2.4.1 [[GetPrototypeOf]] ( )
  1. If IsPlatformObjectSameOrigin(this) is true, then return ! OrdinaryGetPrototypeOf(this).

  2. Return null.

7.2.4.2 [[SetPrototypeOf]] ( V )
  1. Return ! SetImmutablePrototype(this, V).

7.2.4.3 [[IsExtensible]] ( )
  1. Return true.

7.2.4.4 [[PreventExtensions]] ( )
  1. falseを返す。

7.2.4.5 [[GetOwnProperty]] ( P )
  1. If IsPlatformObjectSameOrigin(this) is true, then:

    1. Let desc be OrdinaryGetOwnProperty(this, P).

    2. If the value of the [[DefaultProperties]] internal slot of this contains P, then set desc.[[Configurable]] to true.

    3. Return desc.

  2. Let property be CrossOriginGetOwnPropertyHelper(this, P).

  3. If property is not undefined, then return property.

  4. Return ? CrossOriginPropertyFallback(P).

7.2.4.6 [[DefineOwnProperty]] ( P, Desc )
  1. If IsPlatformObjectSameOrigin(this) is true, then:

    1. If the value of the [[DefaultProperties]] internal slot of this contains P, then return false.

    2. Return ? OrdinaryDefineOwnProperty(this, P, Desc).

  2. Throw a "SecurityError" DOMException.

7.2.4.7 [[Get]] ( P, Receiver )
  1. If IsPlatformObjectSameOrigin(this) is true, then return ? OrdinaryGet(this, P, Receiver).

  2. Return ? CrossOriginGet(this, P, Receiver).

7.2.4.8 [[Set]] ( P, V, Receiver )
  1. If IsPlatformObjectSameOrigin(this) is true, then return ? OrdinarySet(this, P, V, Receiver).

  2. Return ? CrossOriginSet(this, P, V, Receiver).

7.2.4.9 [[Delete]] ( P )
  1. If IsPlatformObjectSameOrigin(this) is true, then return ? OrdinaryDelete(this, P).

  2. Throw a "SecurityError" DOMException.

7.2.4.10 [[OwnPropertyKeys]] ( )
  1. If IsPlatformObjectSameOrigin(this) is true, then return OrdinaryOwnPropertyKeys(this).

  2. Return CrossOriginOwnPropertyKeys(this).

7.2.5 Historyインターフェイス

History

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+

Window/history

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
enum ScrollRestoration { "auto", "manual" };

[Exposed=Window]
interface History {
  readonly attribute unsigned long length;
  attribute ScrollRestoration scrollRestoration;
  readonly attribute any state;
  undefined go(optional long delta = 0);
  undefined back();
  undefined forward();
  undefined pushState(any data, DOMString unused, optional USVString? url = null);
  undefined replaceState(any data, DOMString unused, optional USVString? url = null);
};
history.length

History/length

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

現在のトラバース可能なナビゲート可能の全体のセッション履歴エントリーの数を返す。

history.scrollRestoration

History/scrollRestoration

Support in all current engines.

Firefox46+Safari11+Chrome46+
Opera?Edge79+
Edge (Legacy)?Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

アクティブなセッション履歴エントリースクロール復元モードを返す。

history.scrollRestoration = value

アクティブなセッション履歴エントリースクロール復元モードvalueに設定する。

history.state

History/state

Support in all current engines.

Firefox4+Safari6+Chrome19+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

JavaScript値に逆シリアル化された、アクティブなセッション履歴エントリーシリアル化された状態を返す。

history.go()

現在のページをリロードする。

history.go(delta)

History/go

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

現在のトラバース可能なナビゲート可能の全体のセッション履歴エントリーリストで、指定された数のステップを前後に移動する。

ゼロ差分は、現在のページをリロードする。

差分が範囲外の場合、何もしない。

history.back()

History/back

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

現在のトラバース可能なナビゲート可能の全体のセッション履歴エントリーリストで1ステップ戻る。

前のページが存在しない場合、何もしない。

history.forward()

History/forward

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

現在のトラバース可能なナビゲート可能の全体のセッション履歴エントリーリストで1ステップ進める。

次のページが存在しない場合、何もしない。

history.pushState(data, "")

History/pushState

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+

シリアル化された状態dataのシリアル化に設定して、セッション履歴に新しいエントリーを追加する。アクティブな履歴エントリーURLがコピーされ、新しいエントリーのURLに使用される。

(2番目のパラメーターは歴史的な理由で存在し、省略することはできない。空の文字列を渡すことは慣例的なものである。)

history.pushState(data, "", url)

シリアル化された状態dataのシリアル化に設定し、URLurlに設定して、セッション履歴に新しいエントリーを追加する。

現在のDocumentがURLをurl書き換えることができない場合、"SecurityError" DOMExceptionが投げられる。

(2番目のパラメーターは歴史的な理由で存在し、省略することはできない。空の文字列を渡すことは慣例的なものである。)

history.replaceState(data, "")

History/replaceState

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android11.5+

アクティブなセッション履歴エントリーシリアル化された状態dataの構造化されたクローンに更新する。

(2番目のパラメーターは歴史的な理由で存在し、省略することはできない。空の文字列を渡すことは慣例的なものである。)

history.replaceState(data, "", url)

アクティブなセッション履歴エントリーシリアル化された状態dataの構造化されたクローンに更新し、そのURLurlに更新する。

現在のDocumentがURLをurl書き換えることができない場合、"SecurityError" DOMExceptionが投げられる。

(2番目のパラメーターは歴史的な理由で存在し、省略することはできない。空の文字列を渡すことは慣例的なものである。)

A Document has a history object, a History object.

The history getter steps are to return this's associated Document's history object.


Each History object has state, initially null.

Each History object has a length, a non-negative integer, initially 0.

Each History object has an index, a non-negative integer, initially 0.

Although the index is not directly exposed, it can be inferred from changes to the length during synchronous navigations. In fact, that is what it's used for.

The length getter steps are:

  1. If this's relevant global object's associated Document is not fully active, then throw a "SecurityError" DOMException.

  2. Return this's length.

The scrollRestoration getter steps are:

  1. If this's relevant global object's associated Document is not fully active, then throw a "SecurityError" DOMException.

  2. Return this's node navigable's active session history entry's scroll restoration mode.

The scrollRestoration setter steps are:

  1. If this's relevant global object's associated Document is not fully active, then throw a "SecurityError" DOMException.

  2. Set this's node navigable's active session history entry's scroll restoration mode to the given value.

The state getter steps are:

  1. If this's relevant global object's associated Document is not fully active, then throw a "SecurityError" DOMException.

  2. Return this's state.

The go(delta) method steps are to delta traverse this given delta.

The back() method steps are to delta traverse this given −1.

The forward() method steps are to delta traverse this given +1.

To delta traverse a History object history given an integer delta:

  1. Let document be history's relevant global object's associated Document.

  2. If document is not fully active, then throw a "SecurityError" DOMException.

  3. If delta is 0, then reload document's node navigable.

  4. Traverse the history by a delta given document's node navigable's traversable navigable, delta, and document.

The pushState(data, unused, url) method steps are to run the shared history push/replace state steps given this, data, url, and "push".

The replaceState(data, unused, url) method steps are to run the shared history push/replace state steps given this, data, url, and "replace".

The shared history push/replace state steps, given a History history, a value data, a scalar value string-or-null url, and a history handling behavior historyHandling, are:

  1. Let document be history's associated Document.

  2. If document is not fully active, then throw a "SecurityError" DOMException.

  3. Optionally, return. (For example, the user agent might disallow calls to these methods that are invoked on a timer, or from event listeners that are not triggered in response to a clear user action, or that are invoked in rapid succession.)

  4. Let serializedData be StructuredSerializeForStorage(data). 例外を再度投げる。

  5. Let newURL be document's URL.

  6. If url is not null, then:

    1. Parse url, relative to the relevant settings object of history.

    2. If that fails, then throw a "SecurityError" DOMException.

    3. Set newURL to the resulting URL record.

    4. If document cannot have its URL rewritten to newURL, then throw a "SecurityError" DOMException.

  7. Run the URL and history update steps given document and newURL, with serializedData set to serializedData and historyHandling set to historyHandling.

User agents may limit the number of state objects added to the session history per page. If a page hits the implementation-defined limit, user agents must remove the entry immediately after the first entry for that Document object in the session history after having added the new entry. (Thus the state history acts as a FIFO buffer for eviction, but as a LIFO buffer for navigation.)

A Document document can have its URL rewritten to a URL targetURL if the following algorithm returns true:

  1. Let documentURL be document's URL.

  2. If targetURL and documentURL differ in their scheme, username, password, host, or port components, then return false.

  3. If targetURL's scheme is an HTTP(S) scheme, then return true. (Differences in path, query, and fragment are allowed for http: and https: URLs.)

  4. If targetURL's scheme is "file", and targetURL and documentURL differ in their path component, then return false. (Differences in query and fragment are allowed for file: URLs.)

  5. If targetURL and documentURL differ in their path component or query components, then return false. (Only differences in fragment are allowed for other types of URLs.)

  6. Return true.

document's URLtargetURLcan have its URL rewritten
https://example.com/homehttps://example.com/home#about
https://example.com/homehttps://example.com/home?page=shop
https://example.com/homehttps://example.com/shop
https://example.com/homehttps://user:pass@example.com/home
https://example.com/homehttp://example.com/home
file:///path/to/xfile:///path/to/x#hash
file:///path/to/xfile:///path/to/x?search
file:///path/to/xfile:///path/to/y
about:blankabout:blank#hash
about:blankabout:blank?search
about:blankabout:srcdoc
data:text/html,foodata:text/html,foo#hash
data:text/html,foodata:text/html,foo?search
data:text/html,foodata:text/html,bar
data:text/html,foodata:bar
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43#hash
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43?search
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43blob:https://example.com/anything
blob:https://example.com/77becafe-657b-4fdc-8bd3-e83aaa5e8f43blob:path

DocumentURLのみが重要であり、その生成元は重要ではないことに注意する。継承された生成元をもつabout:blank Document、サンフォボックスiframe、またはdocument.domainセッターが使用されている場合のように、これらが一致しないことがある。

ユーザーはいくつかの座標に常にあり、ユーザーが後で再開するための特定の座標に対応するページをブックマークできるような、ユーザーがラインに沿って移動できるゲームを考える。

そのようなゲームでx=5位置を実装する静的ページは次のようになる:

<!DOCTYPE HTML>
<!-- this is https://example.com/line?x=5 -->
<html lang="en">
<title>Line Game - 5</title>
<p>You are at coordinate 5 on the line.</p>
<p>
 <a href="?x=6">Advance to 6</a> or
 <a href="?x=4">retreat to 4</a>?
</p>

このようなシステムの問題点は、毎回ユーザーがクリックするとページ全体をリロードする必要があることにある。ここで、代わりにスクリプトを使用して、リロードを行うための別の方法:

<!DOCTYPE HTML>
<!-- this starts off as https://example.com/line?x=5 -->
<html lang="en">
<title>Line Game - 5</title>
<p>You are at coordinate <span id="coord">5</span> on the line.</p>
<p>
 <a href="?x=6" onclick="go(1); return false;">Advance to 6</a> or
 <a href="?x=4" onclick="go(-1); return false;">retreat to 4</a>?
</p>
<script>
 var currentPage = 5; // prefilled by server
 function go(d) {
   setupPage(currentPage + d);
   history.pushState(currentPage, "", '?x=' + currentPage);
 }
 onpopstate = function(event) {
   setupPage(event.state);
 }
 function setupPage(page) {
   currentPage = page;
   document.title = 'Line Game - ' + currentPage;
   document.getElementById('coord').textContent = currentPage;
   document.links[0].href = '?x=' + (currentPage+1);
   document.links[0].textContent = 'Advance to ' + (currentPage+1);
   document.links[1].href = '?x=' + (currentPage-1);
   document.links[1].textContent = 'retreat to ' + (currentPage-1);
 }
</script>

スクリプトをもたないシステムにおいて、前の例と同じように動作する。しかし、同じ体験に対するネットワークアクセスが存在しないので、スクリプトをサポートするユーザーは現在はるかに速く移動できる。さらに、経験に反して、ユーザーは単にナイーブなスクリプトベースのアプローチ、ブックマーク、およびセッション履歴の移動が依然として動作する必要がある。

上記の例において、pushState()メソッドへのdata引数は、サーバーに送信されるものと同じ情報であるが、スクリプトはURLにユーザーが移動するたびに解析する必要はないので、より便利な形式となる。

ほとんどのアプリケーションは、すべての履歴エントリーに同じスクロール復元モード値を使用したいと考えている。これを実現するために、できるだけ早くscrollRestoration属性を設定して(たとえば、文書のhead要素の最初のscript要素で)、履歴セッションに追加されたエントリーが確実に希望のスクロール復元モードになるようにする。

<head>
  <script>
       if ('scrollRestoration' in history)
            history.scrollRestoration = 'manual';
  </script>
</head>
   
7.2.6.1 PopStateEventインターフェイス

PopStateEvent

Support in all current engines.

Firefox4+Safari6+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+
[Exposed=Window]
interface PopStateEvent : Event {
  constructor(DOMString type, optional PopStateEventInit eventInitDict = {});

  readonly attribute any state;
};

dictionary PopStateEventInit : EventInit {
  any state = null;
};
event.state

pushState()またはreplaceState()へ提供される情報のコピーを返す。

The state attribute must return the value it was initialized to. It represents the context information for the event, or null, if the state represented is the initial state of the Document.

7.2.6.2 HashChangeEventインターフェイス

HashChangeEvent

Support in all current engines.

Firefox3.6+Safari5+Chrome8+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android?Safari iOS5+Chrome Android?WebView Android?Samsung Internet?Opera Android11+
[Exposed=Window]
interface HashChangeEvent : Event {
  constructor(DOMString type, optional HashChangeEventInit eventInitDict = {});

  readonly attribute USVString oldURL;
  readonly attribute USVString newURL;
};

dictionary HashChangeEventInit : EventInit {
  USVString oldURL = "";
  USVString newURL = "";
};
event.oldURL

HashChangeEvent/oldURL

Support in all current engines.

Firefox6+Safari5.1+Chrome8+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

以前に現在であったセッション履歴のエントリーURLを返す。

event.newURL

HashChangeEvent/newURL

Support in all current engines.

Firefox6+Safari5.1+Chrome8+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android12.1+

今現在であるセッション履歴のエントリーURLを返す。

The oldURL attribute must return the value it was initialized to. It represents context information for the event, specifically the URL of the session history entry that was traversed from.

The newURL attribute must return the value it was initialized to. It represents context information for the event, specifically the URL of the session history entry that was traversed to.

7.2.6.3 PageTransitionEventインターフェイス

PageTransitionEvent

Support in all current engines.

Firefox1.5+Safari5+Chrome4+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android?
[Exposed=Window]
interface PageTransitionEvent : Event {
  constructor(DOMString type, optional PageTransitionEventInit eventInitDict = {});

  readonly attribute boolean persisted;
};

dictionary PageTransitionEventInit : EventInit {
  boolean persisted = false;
};
event.persisted

PageTransitionEvent/persisted

Support in all current engines.

Firefox11+Safari5+Chrome4+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android?Safari iOS4+Chrome Android?WebView Android37+Samsung Internet?Opera Android?

pageshowに対して、ページが新しく読み込まれている(およびloadイベントが発生する)場合にfalseを返す。そうでなければ、trueを返す。

pagehideイベントに対して、ページが最後の時間まで出かける場合はfalseを返す。そうでなければtrueを返す。これは、ユーザーがこのページに戻った場合(Documentsalvageable状態がtrueのままの場合)にページが再利用される可能性があることを意味する。

ページがサルベージ不能になる原因には、次のものがある:

The persisted attribute must return the value it was initialized to. It represents the context information for the event.

To fire a page transition event named eventName at a Window window with a boolean persisted, fire an event named eventName at window, using PageTransitionEvent, with the persisted attribute initialized to persisted, the cancelable attribute initialized to true, the bubbles attribute initialized to true, and legacy target override flag set.

The values for cancelable and bubbles don't make any sense, since canceling the event does nothing and it's not possible to bubble past the Window object. They are set to true for historical reasons.

7.2.6.4 BeforeUnloadEventインターフェイス

BeforeUnloadEvent

Support in all current engines.

Firefox1.5+Safari7+Chrome30+
Opera?Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android37+Samsung Internet3.0+Opera Android?
[Exposed=Window]
interface BeforeUnloadEvent : Event {
  attribute DOMString returnValue;
};

BeforeUnloadEvent固有の初期化メソッドは存在しない。

BeforeUnloadEventインターフェイスは、イベントをキャンセルするだけでなく、returnValue属性を空文字列以外の値に設定することで、アンロードがユーザーによってキャンセルされたかどうかをチェックできるようにするレガシーインターフェイスである。著者は、returnValueを使用する代わりに、preventDefault()メソッド、またはイベントをキャンセルするその他の手段を使用すべきである。

The returnValue attribute controls the process of checking if unloading is user-canceled. When the event is created, the attribute must be set to the empty string. On getting, it must return the last value it was set to. On setting, the attribute must be set to the new value.

This attribute is a DOMString only for historical reasons. Any value besides the empty string will be treated as a request to ask the user for confirmation.