1. 7.10 セッション履歴およびナビゲーション
      1. 7.10.1 ブラウジングセッション
      2. 7.10.2 ブラウジングコンテキストのセッション履歴
      3. 7.10.3 Historyインターフェイス
      4. 7.10.4 Implementation notes for session history
      5. 7.10.5 Locationインターフェイス
        1. 7.10.5.1 [[GetPrototypeOf]] ( )
        2. 7.10.5.2 [[SetPrototypeOf]] ( V )
        3. 7.10.5.3 [[IsExtensible]] ( )
        4. 7.10.5.4 [[PreventExtensions]] ( )
        5. 7.10.5.5 [[GetOwnProperty]] ( P )
        6. 7.10.5.6 [[DefineOwnProperty]] ( P, Desc )
        7. 7.10.5.7 [[Get]] ( P, Receiver )
        8. 7.10.5.8 [[Set]] ( P, V, Receiver )
        9. 7.10.5.9 [[Delete]] ( P )
        10. 7.10.5.10 [[OwnPropertyKeys]] ( )

7.10 セッション履歴およびナビゲーション

7.10.1 ブラウジングセッション

ブラウジングセッションは…である。 ブラウジングセッションの定義については、whatwg/html issue #4782およびwhatwg/html issue #5350を参照のこと。 `Cross-Origin-Opener-Policy`ヘッダーまたはナビゲーションのために置き換えることができないことを除いて、これはトップレベルブラウジングコンテキストにほぼ類似している。

トップレベルブラウジングコンテキストには、ブラウジングセッションであるブラウジングセッションが関連付けられている。

環境設定オブジェクトenvironmentブラウジングセッションは、次の手順を実行した結果である:

  1. Assert: environment's global object is a Window.

  2. Return environment's global object's browsing context's top-level browsing context's browsing session.

7.10.2 ブラウジングコンテキストのセッション履歴

ブラウジングコンテキスト内のDocumentの配列は、そのセッション履歴である。子ブラウジングコンテキストを含む各ブラウジングコンテキストは、個別のセッション履歴を持つ。ブラウジングコンテキストのセッション履歴は、セッション履歴のエントリーのフラットなリストから成る。

ブラウジングコンテキストセッション履歴における各Documentオブジェクトは、同じ基礎となるセッション履歴をすべてモデル化しなければならない、一意なHistoryオブジェクトに関連付けられる。

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


セッション履歴エントリーは、以下のアイテムをもつ構造体である:

シリアライズされた状態は、ユーザーインターフェイスの状態を表すオブジェクトを(StructuredSerializeForStorage経由で)シリアライズしたものである。非公式に"状態オブジェクト"と呼ぶこともあるが、これは著者から提供されたユーザーインターフェイスの状態を表すオブジェクトであり、あるいは、シリアライズされた状態をデシリアライズ(StructuredDeserialize経由で)して作成されたオブジェクトでもある。

ページは、シリアライズされた状態をセッション履歴に追加することができる。ユーザー(またはスクリプト)が履歴に戻るとき、これらはデシリアイズされスクリプトに返されるため、著者は1ページのアプリケーションでも"ナビゲーション"メタファーを使用できるようになる。

シリアライズされた状態は、主に2つの目的で使用されることを意図している:1つは、事前に準備された状態の記述をURLに格納することで、単純な場合には著者が解析を行う必要がないようにすることである(ただし、ユーザーによって渡されたURLを処理するためには解析が必要になるので、マイナーな最適化に過ぎない)。もう1つは、現在のDocumentインスタンスにのみ適用され、新しい Documentを開いた場合に再構築しなければならないため、URL には保存されないような状態を作者が保存できるようにすることである。

後者の例は、ユーザーが戻った場合同じ場所にアニメーションさせることができるように、ポップアップdivがアニメーション化するために作られた正確な座標を追跡するようなものになるだろう。またその代わりに、前後に行くときに、情報が再度フェッチする必要がないよう、URL内の情報に基づいてサーバーからフェッチされるデータのキャッシュにポインターを保持するために使用できる。

スクロール復元モードは、エントリーに移動するときに、ユーザーエージェントが永続化されたスクロール位置(存在する場合)を復元すべきかどうかを示す。スクロール復元モードは次のいずれかである:

"auto"
ユーザーエージェントは、ナビゲーション時にスクロール位置を復元する責任がある。
"manual"
ページはスクロール位置を復元する責任があり、ユーザーエージェントは自動的に復元を試みない。

セッション履歴内の複数の連続したエントリーは、同じ文書を共有することができる。これは、通常のナビゲーションを介して最初のエントリーに到達し、かつhistory.pushState()を介して次のエントリーが追加された場合に発生する可能性がある。または、フラグメントへのナビゲーションを介して発生する可能性がある。

同じDocumentを共有する(したがって、特定の文書の単に異なる状態である)すべてのエントリーは、定義により連続する。

User agents may discard the documents of entries with non-null documents, as long as the following conditions are met:

Apart from these restrictions, this standard does not specify when user agents should discard an entry's document, versus keeping it cached.

Discarding a Document will set the corresponding document item of any session history entries to null. Subsequent navigations to those entries will result in the creation of a new Document object, and set the document item to it.


任意の時点で、セッション履歴のエントリーの1つは、現在のエントリーである。これは、ブラウジングコンテキストアクティブ文書を表すエントリーである。現在のエントリーであるそれぞれのエントリーは、この仕様で定義されるアルゴリズムによって変更される。たとえばセッション履歴走査中など。

現在のエントリーは通常、ナビゲーション時に作成される最初のエントリーである。しかし、上記のように、同じ文書を共有する連続したエントリーの1つにすることもできる。

ブラウジングコンテキスト内の各Documentはまた、最新のエントリーを持つことができる。これは、ブラウジングコンテキストセッション履歴が最後にたどられたDocumentのエントリーである。 Documentが作成されるとき、最初は最新のエントリーを持たない。

7.10.3 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);
};
window.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+

ジョイントセッション履歴内のエントリーの数を返す。

window.history.scrollRestoration [ = value ]

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?

セッション履歴の現在のエントリーのスクロール復元モードを返す。

セッション履歴の現在のエントリーのスクロール復元モードを変更する設定が可能である。

window.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+

オブジェクトにデシリアライズされた、現在のシリアライズされた状態を返す。

window.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+

ジョイントセッション履歴内のステップの指定した数の前後に進む。

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

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

window.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つのステップに戻る。

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

window.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つのステップに進む。

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

window.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番目のパラメーターは歴史的な理由で存在し、省略することはできない。空の文字列を渡すことは慣例的なものである。)

window.history.pushState(data, "", url)

指定されたdataが関連付けられ、そのURLがurlに設定される新しいエントリーをセッション履歴にプッシュする。

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

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

window.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番目のパラメーターは歴史的な理由で存在し、省略することはできない。空の文字列を渡すことは慣例的なものである。)

window.history.replaceState(data, "", url)

現在のセッション履歴エントリーに保存されているデータをdataに更新し、そのURLをurlに更新する。

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

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

トップレベルブラウジングコンテキストジョイントセッション履歴は、ジョイントセッション履歴の現在のエントリーを除いて削除されたそれぞれのセッション履歴において現在のエントリーであるすべてのエントリーとともに、トップレベルブラウジングコンテキストを共有するすべての完全にアクティブなDocumentオブジェクトのすべてのブラウジングコンテキストに属するすべてのセッション履歴の結合である。

ジョイントセッション履歴の現在のエントリーは、最近そのセッション履歴内の現在のエントリーになったエントリーである。

ジョイントセッション履歴内のエントリーは、それぞれのセッション履歴に追加された時点で時系列に並べられる。各エントリーはインデックスを持つ。最古のエントリーのインデックスは0を持ち、後続のエントリーは連続して増加する整数(1、2、3など)を番号付けされる。

ブラウジングコンテキスト内の各Documentは、異なるイベントループがあるかもしれないので、ジョイントセッション履歴の実際の状態は、不明瞭にできる。たとえば、2つの兄弟iframe要素は、同時に1つの一意な生成元から別のものに互いに横断でき、それらの正確な順序は明確に定義されないかもしれない。それらは後にお互いを知るかもしれないので、同様に、それらはジョイントセッション履歴の長さについて同意しないかもしれない。

Each History object has state, initially null.

The length getter steps are:

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

  2. Return the number of entries in the top-level browsing context's joint session history.

The actual entries are not accessible from script.

The scrollRestoration getter steps are:

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

  2. Return this's session history's current entry's scroll restoration mode.

The scrollRestoration setter steps are:

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

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

The state getter steps are:

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

  2. Return this's state.

The go(delta) method steps are:

  1. Let document be this's associated Document.

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

  3. If delta is 0, then act as if the location.reload() method was called, and return.

  4. Traverse the history by a delta with delta and document's browsing context.

The back() method steps are:

  1. Let document be this's associated Document.

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

  3. Traverse the history by a delta with −1 and document's browsing context.

The forward() method steps are:

  1. Let document be this's associated Document.

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

  3. Traverse the history by a delta with +1 and document's browsing context.


Each top-level browsing context has a session history traversal queue, initially empty, to which tasks can be added.

Each top-level browsing context, when created, must begin running the following algorithm, known as the session history event loop for that top-level browsing context, in parallel:

  1. Wait until this top-level browsing context's session history traversal queue is not empty.

  2. Pull the first task from this top-level browsing context's session history traversal queue, and execute it.

  3. Return to the first step of this algorithm.

The session history event loop helps coordinate cross-browsing-context transitions of the joint session history: since each browsing context might, at any particular time, have a different event loop (this can happen if the user navigates from example.com to shop.example), transitions would otherwise have to involve cross-event-loop synchronization.


To traverse the history by a delta given delta and browsing context source browsing context, the user agent must append a task to this top-level browsing context's session history traversal queue, the task consisting of running the following steps:

  1. If the index of the current entry of the joint session history plus delta is less than zero or greater than or equal to the number of items in the joint session history, then return.

  2. Let specified entry be the entry in the joint session history whose index is the sum of delta and the index of the current entry of the joint session history.

  3. Let specified browsing context be the browsing context of the specified entry.

  4. If source browsing context is not allowed to navigate specified browsing context, then return.

  5. If the specified browsing context's active document's unload counter is greater than 0, then return.

  6. Queue a global task on the history traversal task source given specified browsing context's active window to perform the following steps:

    1. If there is an ongoing attempt to navigate specified browsing context that has not yet matured (i.e. it has not passed the point of making its Document the active document), then cancel that attempt to navigate the browsing context.

    2. If the specified browsing context's active document is not the same Document as the Document of the specified entry, then run these substeps:

      1. If the result of calling prompt to unload with the active document of the specified browsing context is "refuse", then abort these steps.

      2. Unload the active document of the specified browsing context.

    3. Traverse the history of the specified browsing context to the specified entry with explicitHistoryNavigation set to true.

When the user navigates through a browsing context, e.g. using a browser's back and forward buttons, the user agent must traverse the history by a delta with a delta equivalent to the action specified by the user and the browsing context being operated on.


The URL and history update steps, given a Document document, a URL newURL, an optional serialized state-or-null serializedData (default null), and an optional boolean isPush (default false), are:

  1. Let browsingContext be document's browsing context.

  2. If browsingContext is still on its initial about:blank Document, then set isPush to false.

    This means that pushState() on an initial about:blank Document behaves as a replaceState() call.

  3. If isPush is true, then:

    1. Remove all the entries in browsingContext's session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

      This doesn't necessarily have to affect the user agent's user interface.

    2. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context's document family.

    3. Save persisted state to the current entry.

    4. Add a session history entry entry to browsingContext's session history, after the current entry, with

    5. Update the current entry to be this newly added entry.

  4. Otherwise:

    1. Let entry be browsingContext's session history's current entry.

    2. Set entry's URL to newURL.

    3. If serializedData is not null, then set entry's serialized state to serializedData.

    4. Update entry so that it represents a GET request, if it currently represents a non-GET request (e.g. it was the result of a POST submission).

      What does this mean? This is not a part of the definition of session history entry.

  5. Set document's URL to newURL.

    Since this is neither a navigation of the browsing context nor a history traversal, it does not cause a hashchange event to be fired.

  6. If serializedData is not null, then:

    1. Let state be StructuredDeserialize(serializedData, document's relevant realm). If this throws an exception, catch it, ignore the exception, and set state to null.

    2. Set document's History instance's state to state.

  7. Set the current entry's document's latest entry to the current entry.

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

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

The shared history push/replace state steps, given a History history, a value data, a scalar value string-or-null url, and a boolean isPush, 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 the session history's current entry'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 isPush set to isPush.

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.10.4 Implementation notes for session history

この節は非規範的である。

The History interface is not meant to place restrictions on how implementations represent the session history to the user.

For example, session history could be implemented in a tree-like manner, with each page having multiple "forward" pages. This specification doesn't define how the linear list of pages in the history object are derived from the actual session history as seen from the user's perspective.

Similarly, a page containing two iframes has a history object distinct from the iframes' history objects, despite the fact that typical web browsers present the user with just one "Back" button, with a session history that interleaves the navigation of the two inner frames and the outer page.

Security: It is suggested that to avoid letting a page "hijack" the history navigation facilities of a UA by abusing pushState(), the UA provide the user with a way to jump back to the previous page (rather than just going back to the previous state). For example, the back button could have a drop down showing just the pages in the session history, and not showing any of the states. Similarly, an aural browser could have two "back" commands, one that goes back to the previous state, and one that jumps straight back to the previous page.

For both pushState() and replaceState(), user agents are encouraged to prevent abuse of these APIs via too-frequent calls or over-large state objects. As detailed above, the algorithm explicitly allows user agents to ignore any such calls when appropriate.

7.10.5 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 the active document of their Document's browsing context, and allow the current entry of the browsing context's session history to be changed, by adding or replacing entries in the history object.

[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 this Location object's 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 browsing context of the Document with which this Location object is associated.

  3. Loop: If current has no parent browsing context, jump to the step labeled end.

  4. Let current be current's parent browsing context.

  5. Append the serialization of current's active document's origin to output.

  6. loopにラベル付けされた手順に戻る。

  7. End: Return output.

To Location-object navigate, given a URL url and an optional history handling behavior historyHandling (default "default"):

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

  2. Let sourceBrowsingContext be the incumbent global object's browsing context.

  3. If this Location object'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 browsingContext to url, with exceptionsEnabled set to true, historyHandling set to historyHandling, and the source browsing context set to sourceBrowsingContext.

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 TypeError exception.

  3. Location-object navigate given 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 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 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 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 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 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 copyURL as url, and query state as state override.

  6. Location-object navigate 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 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 given 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 given the resulting URL record and "replace".

The replace() method intentionally has no security check.

The reload() method steps are to run the appropriate steps from the following list:

If this's relevant Document is null

Return.

If this's relevant Document's origin is not same origin-domain with the entry settings object's origin

Throw a "SecurityError" DOMException.

If the currently executing task is the dispatch of a resize event in response to the user resizing the browsing context

Repaint the browsing context and return.

If the browsing context's active document is an iframe srcdoc document

Reprocess the iframe attributes of the browsing context's container.

そうでなければ

Navigate the browsing context to this's relevant Document's URL, with exceptionsEnabled set to true, historyHandling set to "reload", and the source browsing context set to the browsing context being navigated.

When a user requests that the active document of a browsing context be reloaded through a user interface element, the user agent should navigate the browsing context to the same resource as that Document, with historyHandling set to "reload". In the case of non-idempotent methods (e.g., HTTP POST), the user agent should prompt the user to confirm the operation first, since otherwise transactions (e.g., purchases or database modifications) could be repeated. User agents may allow the user to explicitly override any caches when reloading.


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.10.5.1 [[GetPrototypeOf]] ( )
  1. If IsPlatformObjectSameOrigin(this) is true, then return ! OrdinaryGetPrototypeOf(this).

  2. Return null.

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

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

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

7.10.5.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.10.5.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.10.5.7 [[Get]] ( P, Receiver )
  1. If IsPlatformObjectSameOrigin(this) is true, then return ? OrdinaryGet(this, P, Receiver).

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

7.10.5.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.10.5.9 [[Delete]] ( P )
  1. If IsPlatformObjectSameOrigin(this) is true, then return ? OrdinaryDelete(this, P).

  2. Throw a "SecurityError" DOMException.

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

  2. Return CrossOriginOwnPropertyKeys(this).