1. 7 ウェブページの読み込み
    1. 7.1 ブラウジングコンテキスト
      1. 7.1.1 ネストされたブラウジングコンテキスト
        1. 7.1.1.1 DOM内でネストされたブラウジングコンテキストを操作する
      2. 7.1.2 補助ブラウジングコンテキスト
        1. 7.1.2.1 DOM内の補助ブラウジングコンテキストを操作する
      3. 7.1.3 セキュリティー
      4. 7.1.4 Groupings of browsing contexts
      5. 7.1.5 ブラウジングコンテキスト名
      6. 7.1.6 Script settings for browsing contexts
    2. 7.2 Security infrastructure for Window, WindowProxy, and Location objects
      1. 7.2.1 Integration with IDL
      2. 7.2.2 Shared internal slot: [[CrossOriginPropertyDescriptorMap]]
      3. 7.2.3 Shared abstract operations
        1. 7.2.3.1 CrossOriginProperties ( O )
        2. 7.2.3.2 IsPlatformObjectSameOrigin ( O )
        3. 7.2.3.3 CrossOriginGetOwnPropertyHelper ( O, P )
        4. 7.2.3.4 CrossOriginGet ( O, P, Receiver )
        5. 7.2.3.5 CrossOriginSet ( O, P, V, Receiver )
        6. 7.2.3.6 CrossOriginOwnPropertyKeys ( O )
    3. 7.3 Windowオブジェクト
      1. 7.3.1 名前でブラウジングコンテキストを作成および操作するためのAPI
      2. 7.3.2 他のブラウジングコンテキストへのアクセス
      3. 7.3.3 Windowオブジェクトの名前付きアクセス
      4. 7.3.4 Garbage collection and browsing contexts
      5. 7.3.5 ブラウジングコンテキストを閉じる
      6. 7.3.6 ブラウザーインターフェイス要素
    4. 7.4 The WindowProxy exotic object
      1. 7.4.1 [[GetPrototypeOf]] ( )
      2. 7.4.2 [[SetPrototypeOf]] ( V )
      3. 7.4.3 [[IsExtensible]] ( )
      4. 7.4.4 [[PreventExtensions]] ( )
      5. 7.4.5 [[GetOwnProperty]] ( P )
      6. 7.4.6 [[DefineOwnProperty]] ( P, Desc )
      7. 7.4.7 [[Get]] ( P, Receiver )
      8. 7.4.8 [[Set]] ( P, V, Receiver )
      9. 7.4.9 [[Delete]] ( P )
      10. 7.4.10 [[OwnPropertyKeys]] ( )
    5. 7.5 生成元
      1. 7.5.1 同一生成元制限を緩和する
    6. 7.6 サンドボックス
    7. 7.7 セッション履歴およびナビゲーション
      1. 7.7.1 ブラウジングコンテキストのセッション履歴
      2. 7.7.2 Historyインターフェイス
      3. 7.7.3 Implementation notes for session history
      4. 7.7.4 Locationインターフェイス
        1. 7.7.4.1 [[GetPrototypeOf]] ( )
        2. 7.7.4.2 [[SetPrototypeOf]] ( V )
        3. 7.7.4.3 [[IsExtensible]] ( )
        4. 7.7.4.4 [[PreventExtensions]] ( )
        5. 7.7.4.5 [[GetOwnProperty]] ( P )
        6. 7.7.4.6 [[DefineOwnProperty]] ( P, Desc )
        7. 7.7.4.7 [[Get]] ( P, Receiver )
        8. 7.7.4.8 [[Set]] ( P, V, Receiver )
        9. 7.7.4.9 [[Delete]] ( P )
        10. 7.7.4.10 [[OwnPropertyKeys]] ( )
    8. 7.8 ウェブを閲覧する
      1. 7.8.1 Navigating across documents
      2. 7.8.2 Page load processing model for HTML files
      3. 7.8.3 Page load processing model for XML files
      4. 7.8.4 Page load processing model for text files
      5. 7.8.5 Page load processing model for multipart/x-mixed-replace resources
      6. 7.8.6 Page load processing model for media
      7. 7.8.7 Page load processing model for content that uses plugins
      8. 7.8.8 Page load processing model for inline content that doesn't have a DOM
      9. 7.8.9 Navigating to a fragment
      10. 7.8.10 履歴走査
        1. 7.8.10.1 Persisted user state restoration
        2. 7.8.10.2 PopStateEventインターフェイス
        3. 7.8.10.3 HashChangeEventインターフェイス
        4. 7.8.10.4 PageTransitionEventインターフェイス
      11. 7.8.11 文書の解放
        1. 7.8.11.1 BeforeUnloadEventインターフェイス
      12. 7.8.12 Aborting a document load
    9. 7.9 オフラインウェブアプリケーション
      1. 7.9.1 導入
        1. 7.9.1.1 レガシーアプリケーションへのオフラインキャッシュのサポート
        2. 7.9.1.2 イベントの概要
      2. 7.9.2 Application caches
      3. 7.9.3 キャッシュマニフェスト構文
        1. 7.9.3.1 サンプルマニフェスト
        2. 7.9.3.2 キャッシュマニフェストの記述
        3. 7.9.3.3 Parsing cache manifests
      4. 7.9.4 Downloading or updating an application cache
      5. 7.9.5 The application cache selection algorithm
      6. 7.9.6 Changes to the networking model
      7. 7.9.7 Expiring application caches
      8. 7.9.8 Disk space
      9. 7.9.9 Security concerns with offline applications caches
      10. 7.9.10 アプリケーションキャッシュAPI
      11. 7.9.11 ブラウザーの状態

7 ウェブページの読み込み

This section describes features that apply most directly to Web browsers. Having said that, except where specified otherwise, the requirements defined in this section do apply to all user agents, whether they are Web browsers or not.

7.1 ブラウジングコンテキスト

ブラウジングコンテキストDocumentオブジェクトがユーザーに提示される環境である。

ウェブブラウザーのタブまたはウィンドウは通常、iframeまたはframeset内のframeを含む、ブラウジングコンテキストを含む。

ブラウジングコンテキストは、対応するWindowProxyオブジェクトを持つ。

ブラウジングコンテキストは、ブラウジングコンテキストが提示されていた、している、またはするだろうDocumentオブジェクトを一覧表示するセッション履歴を持つ。任意の時点で、それぞれのブラウジングコンテキストで1つのDocumentアクティブドキュメントを指定される。Documentのブラウジングコンテキストは、ブラウジングコンテキストが存在しかつ破棄されてない場合に、セッション履歴がDocumentを含むブラウジングコンテキストである。

一般に、Documentオブジェクトがブラウジングコンテキストを持つ限りは、WindowオブジェクトからDocumentオブジェクトへの1対1のマッピングが存在する。2つの例外が存在する。まず、Windowは、マッピングが1対2になるような、同じブラウジングコンテキストにおける2番目のDocumentのプレゼンテーションに対して再利用できる。交換が有効なブラウジングコンテキストが初期about:blank Documentから別のものにナビゲートしたとき、これは起こる。次に、Documentは、マッピングが多対1であるような、document.open()メソッドが使用される場合、複数のWindowオブジェクトを再利用されて終わることができる。

Documentは、関連付けられたブラウジングコンテキストを必ずしも持たない。具体的には、データマイニングツールはブラウジングコンテキストをインスタンス化できないだろう。createDocument()のようなAPIを使用して作成されるDocumentは、ブラウジングコンテキストを持たない。ドキュメントから削除されて以来、iframe要素で当初は作成されたDocumentは、そのブラウジングコンテキストが破棄されたので、関連付けられたブラウジングコンテキストを持たない。


ブラウジングコンテキストは、その作成に関与するブラウジングコンテキストクリエイターブラウジングコンテキストを持つことができる。ブラウジングコンテキスト親ブラウジングコンテキストを持つ場合、それは、そのクリエイターブラウジングコンテキストである。そうでなければ、ブラウジングコンテキストオープナーブラウジングコンテキストを持つ場合、それがそのクリエイターブラウジングコンテキストである。そうでなければ、ブラウジングコンテキスト作成者ブラウジングコンテキストを持たない。

ブラウジングコンテキスト contextクリエイターブラウジングコンテキスト creatorを持つ場合、次のプロパティも持つ。続くもので、contextの作成時でcreator documentcreatorアクティブな文書にする:

クリエイター生成元
creator document生成元
クリエイターURL
creator documentURL
クリエイターベースURL
creator documentベースURL
クリエイターリファラーポリシー
creator documentリファラーポリシー
クリエイターコンテキストセキュリティー
creator document関連する設定オブジェクト上のIs environment settings object a secure context?の結果

To create a new browsing context:

  1. Let browsingContext be a new browsing context.

  2. Call the JavaScript InitializeHostDefinedRealm() abstract operation with the following customizations:

  3. Set up a browsing context environment settings object with realm execution context, and let settingsObject be the result.

  4. Let document be a new Document, marked as an HTML document in quirks mode, whose content type is "text/html", and which is both ready for post-load tasks and completely loaded immediately.

  5. Ensure that document has a single child html node, which itself has two empty child nodes: a head element, and a body element.

  6. Set window's associated Document to document.

  7. Set browsingContext's WindowProxy object's [[Window]] internal slot value to window.

    The internal slot value is updated when navigations occur.

  8. Set the origin of document:

  9. If browsingContext has a creator browsing context, then set document's referrer to the serialization of creator URL.

  10. If browsingContext has a creator browsing context, then set document's referrer policy to the creator referrer policy.

  11. Implement the sandboxing for document.

  12. Set the allow* flags for document.

  13. Set settingsObject's execution ready flag.

  14. Add document to browsingContext's session history.

  15. Return browsingContext.

7.1.1 ネストされたブラウジングコンテキスト

特定の要素(たとえば、iframe要素)は、ブラウジングコンテキストをさらにインスタンス化できる。この要素は、ブラウジングコンテキストコンテナと呼ばれる。

ブラウジングコンテキストコンテナは、ブラウジングコンテキストまたはnullのいずれとなる、ネストされたブラウジングコンテキストを持つ。

ブラウジングコンテキストブラウジングコンテキストコンテナネストされたブラウジングコンテキストである場合、ブラウジングコンテキストは、ブラウジングコンテキストコンテナノード文書経由してネストされると呼ばれる。

次の条件のすべてを保持する場合、ブラウジングコンテキストchildは、別のブラウジングコンテキストparent子ブラウジングコンテキストであると言われる:

ブラウジング コンテキストchildが、子ブラウジングコンテキストでありかつそのブラウジングコンテキストコンテナに単に接続されないだけでなく文書ツリー内である場合、parent文書ツリー子ブラウジングコンテキストである。

ブラウジングコンテキストchild親ブラウジングコンテキストを持ってもよい。もしそのようなブラウジングコンテキストが存在すれば、これは子ブラウジングコンテキストとしてchildを持つ一意なブラウジングコンテキストである。そうでなければ、ブラウジングコンテキストは、親ブラウジングコンテキストを持たない。

ブラウジングコンテキストAA子ブラウジングコンテキストであり、かつB祖先自身であるブラウジングコンテキストA'が存在する場合、またはブラウジングコンテキストABの親ブラウジングコンテキストである場合、ブラウジングコンテキストB祖先であると言われる。

ネストされたブラウジングコンテキストでないブラウジングコンテキストは、親ブラウジングコンテキストを持たず、祖先ブラウジングコンテキストであるすべてのブラウジングコンテキストの最上位ブラウジングコンテキストとなる。

ネストされたブラウジングコンテキストであるブラウジングコンテキストに対する親ブラウジングコンテキストの推移的クロージャは、祖先ブラウジングコンテキストをのリストを与える。

Document d子孫ブラウジングコンテキストのリストは、以下のアルゴリズムによって返される(順序の)リストである:

  1. listを空にする。

  2. dの各子ブラウジングコンテキストd Document存在する要素を介してネストされるので、要素のこれらブラウジングコンテキストをネストするツリー順に、次のサブステップを実行する:

    1. リストlistにその子ブラウジングコンテキストを追加する。

    2. リストlistにその子ブラウジングコンテキストアクティブドキュメントに属する子孫ブラウジングコンテキストのリストを追加する。

  3. 構築されたlistを返す。

A Document is said to be fully active when it has a browsing context and it is the active document of that browsing context, and either its browsing context is a top-level browsing context, or it has a parent browsing context and the Document through which it is nested is itself fully active.

Because they are associated with an element, child browsing contexts are always tied to a specific Document in their parent browsing context. ユーザーエージェントは、ユーザーにがいない自身が完全にアクティブでないDocumentにある要素の子ブラウジングコンテキストと対話することを許可してはならない。

A browsing context that is a nested browsing context can be put into a delaying load events mode. This is used when it is navigated, to delay the load event of its browsing context container before the new Document is created.

ブラウジングコンテキストドキュメントファミリーは、そのブラウジングコンテキストセッション履歴ですべてのDocumentオブジェクト およびすべてのそれらDocumentオブジェクトのドキュメントファミリーの結合で構成される。Documentオブジェクトのドキュメントファミリーは、Documentオブジェクトを介してネストされるブラウジングコンテキストの所有するすべてのドキュメントファミリーの結合で構成される。

The content document of a browsing context container container is the result of the following algorithm:

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

  2. Let context be container's nested browsing context.

  3. Let document be context's active document.

  4. If document's origin and the origin specified by the current settings object are not same origin-domain, then return null.

  5. Return document.

window . top

トップレベルブラウジングコンテキストWindowProxyを返す。

window . parent

親ブラウジングコンテキストに対するWindowProxyを返す。

window . frameElement

ブラウジングコンテキストコンテナElementを返す。

存在しない場合、クロスオリジンの状況でnullを返す。

The top IDL attribute, on getting, must run the following algorithm:

  1. Let windowProxy be this Window object's WindowProxy object.

  2. If there is no browsing context with windowProxy as its WindowProxy object, then return null.

  3. Let context be that browsing context.

  4. If context is a top-level browsing context, then return context's WindowProxy object.

  5. Otherwise, context must have a top-level browsing context (i.e. an ancestor browsing context with no parent browsing context). Return that top-level browsing context's WindowProxy object.

The parent IDL attribute, on getting, must run the following algorithm:

  1. Let windowProxy be this Window object's WindowProxy object.

  2. If there is no browsing context with windowProxy as its WindowProxy object, then return null.

  3. Let context be that browsing context.

  4. If context is a child browsing context of another browsing context parent, then return parent's WindowProxy object.

  5. Otherwise, context must be a top-level browsing context. Return context's WindowProxy object.

The frameElement IDL attribute, on getting, must run the following algorithm:

  1. Let windowProxy be this Window object's WindowProxy object.

  2. If there is no browsing context with windowProxy as its WindowProxy object, then return null.

  3. Let context be that browsing context.

  4. If context is not a nested browsing context, then return null.

  5. Let container be context's browsing context container.

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

  7. Return container.

An example of when these IDL attributes 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 discarded when element was removed from the document.

7.1.2 補助ブラウジングコンテキスト

要素を通じてネストせずにトップレベルブラウジングコンテキストに関連する新しいブラウジングコンテキストを作成することが可能である。このようなブラウジングコンテキストは、補助ブラウジングコンテキストと呼ばれる。補助ブラウジングコンテキストは常にトップレベルブラウジングコンテキストである。

補助ブラウジングコンテキストは、補助ブラウジングコンテキストから作成されたブラウジングコンテキストである、オープナーブラウジングコンテキストを持つ。

存在し、利用可能であり、かつ現在のブラウジングコンテキストが、そのオープナーを解消するのでない場合、取得時に、Windowオブジェクトのopener IDL属性は、現在のブラウジングコンテキストが(そのオープナーブラウジングコンテキスト)を作成されたブラウジングコンテキストWindowProxyオブジェクトを返さなければならない。そうでなければ、nullを返さなければならない。設定時に、新しい値がnullの場合、現在のブラウジングコンテキストオープナーを解消しなければならない。新しい値が何か他のものである場合、ユーザーエージェントはWindowオブジェクトの[[DefineOwnProperty]]初期メソッドを呼ばなければならず、 プロパティキーとしてプロパティ名"opener"を通過し、かつプロパティ記述子としてプロパティ記述子 { [[Value]]: value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }とする。ここでvalueは新しい値である。

If a browsing context has disowned its opener, the value of its window.opener is null. That prevents scripts in the browsing context from changing any properties of its opener browsing context's Window (i.e., the window from which the browsing context was created).

Otherwise, if a browsing context has not disowned its opener, then scripts in that browsing context can use window.opener to change properties of its opener browsing context's Window. For example, a script running in the browsing context can change the value of window.opener.location, causing the opener browsing context to navigate to a completely different document.

7.1.3 セキュリティー

A browsing context A is familiar with a second browsing context B if one of the following conditions is true:


A browsing context A is allowed to navigate a second browsing context B if the following algorithm terminates positively:

  1. If A is not the same browsing context as B, and A is not one of the ancestor browsing contexts of B, and B is not a top-level browsing context, and A's active document's active sandboxing flag set has its sandboxed navigation browsing context flag set, then abort these steps negatively.

  2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:

    1. If this algorithm is triggered by user activation and A's active document's active sandboxing flag set has its sandboxed top-level navigation with user activation browsing context flag set, then abort these steps negatively.

    2. Otherwise, If this algorithm is not triggered by user activation and A's active document's active sandboxing flag set has its sandboxed top-level navigation without user activation browsing context flag set, then abort these steps negatively.

  3. Otherwise, if B is a top-level browsing context, and is neither A nor one of the ancestor browsing contexts of A, and A's Document's active sandboxing flag set has its sandboxed navigation browsing context flag set, and A is not the one permitted sandboxed navigator of B, then abort these steps negatively.

  4. Otherwise, terminate positively!


An element has a browsing context scope origin if its Document's browsing context is a top-level browsing context or if all of its Document's ancestor browsing contexts all have active documents whose origin are the same origin as the element's node document's origin. If an element has a browsing context scope origin, then its value is the origin of the element's node document.

7.1.4 Groupings of browsing contexts

Each browsing context is defined as having a list of one or more directly reachable browsing contexts. These are:

The transitive closure of all the browsing contexts that are directly reachable browsing contexts forms a unit of related browsing contexts.

Each unit of related browsing contexts is then further divided into the smallest number of groups such that every member of each group has an active document with an origin that, through appropriate manipulation of the document.domain attribute, could be made to be same origin-domain with other members of the group, but could not be made the same as members of any other group. Each such group is a unit of related similar-origin browsing contexts.

There is also at most one event loop per unit of related similar-origin browsing contexts (though several units of related similar-origin browsing contexts can have a shared event loop).

7.1.5 ブラウジングコンテキスト名

ブラウジングコンテキストは、ブラウジングコンテキスト名を持つことができる。Unless stated otherwise, it is the empty string.

妥当なブラウジングコンテキスト名は、U+005F LOW LINE文字で始まらない少なくとも1文字をもつ任意の文字列である。(アンダースコアで始まる名前は、特別なキーワードのために予約されている。)

妥当なブラウジングコンテキスト名またはキーワードは、妥当なブラウジングコンテキスト名またはASCII大文字・小文字不区別_blank_self_parent、または_topの1つにマッチするいずれかとなる任意の文字列である。

これらの値は、以下の(非規範的な)テーブルで要約されるように、ページがサンドボックス化されるかどうかに基づいて異なる意味を持つ。この表において、"current"はリンクまたはスクリプト内にあるブラウジングコンテキストを意味し、"parent"はリンクまたはスクリプト内にあるいずれかの親ブラウジングコンテキストを意味し、"top"はリンクまたはスクリプトがあるいずれかのトップレベルブラウジングコンテキストを意味し、"new"はさまざまなユーザー設定とユーザーエージェントのポリシーに次第で、新しいトップレベルブラウジングコンテキストまたは補助ブラウジングコンテキストが作成されることを意味し、"none"は何も起こらないことを意味し、"maybe new"は"allow-popups"キーワードはまたsandbox属性で指定される場合(またはユーザーがサンドボックスを覆う場合)、"new"と同じであり、そうでなければ"none"と同じである。

キーワード 普通の効果 iframeでの効果
sandbox="" sandbox="allow-top-navigation"
リンクおよびフォーム送信に対して、何も指定しない current current current
空文字列 current current current
_blank new maybe new maybe new
_self current current current
親が存在しない場合の_parent current current current
親がまたトップである場合の_parent parent/top none parent/top
存在するがトップでない場合の_parent parent none none
トップが現在である場合の_top current current current
トップが現在でない場合の_top top none top
名前が存在しない new maybe new maybe new
名前が存在しかつ子孫である specified descendant specified descendant specified descendant
名前が存在し現在である current current current
名前が存在しかつトップとなる祖先である specified ancestor none specified ancestor/top
名前が存在しかつトップでない祖先である specified ancestor none none
他の名前が共通のトップとともに存在する specified none none
familiarかつある許可されたサンドボックス化されたナビゲーターである場合、異なるトップをもつ名前が存在する specified specified specified
familiarだがある許可されたサンドボックス化されたナビゲーターでない場合、異なるトップをもつ名前が存在する specified none none
familiarでない、異なるトップをもつ名前が存在する new maybe new maybe new

サンドボックス化されたブラウジングコンテキストの制限のほとんどは、他のアルゴリズムにより適用される。たとえば、下記で与えられるブラウジングコンテキスト名で与えられたをブラウジングコンテキストを選択するための規則でなく、ナビゲーションアルゴリズムとして。


The rules for choosing a browsing context given a browsing context name are as follows. The rules assume that they are being applied in the context of a browsing context, as part of the execution of a task.

  1. If the given browsing context name is the empty string or _self, then the chosen browsing context must be the current one.

  2. If the given browsing context name is _parent, then the chosen browsing context must be the parent browsing context of the current one, unless there isn't one, in which case the chosen browsing context must be the current browsing context.

  3. If the given browsing context name is _top, then the chosen browsing context must be the top-level browsing context of the current one, if there is one, or else the current browsing context.

  4. If the given browsing context name is not _blank and there exists a browsing context whose name is the same as the given browsing context name, and the current browsing context is familiar with that browsing context, and the user agent determines that the two browsing contexts are related enough that it is ok if they reach each other, then that browsing context must be the chosen one. If there are multiple matching browsing contexts, the user agent should select one in some arbitrary consistent manner, such as the most recently opened, most recently focused, or more closely related.

  5. Otherwise, a new browsing context is being requested, and what happens depends on the user agent's configuration and abilities — it is determined by the rules given for the first applicable option from the following list:

    There is no chosen browsing context. The user agent may inform the user that a popup has been blocked.

    If the current browsing context's active document's active sandboxing flag set has the sandboxed auxiliary navigation browsing context flag set.

    Typically, there is no chosen browsing context.

    The user agent may offer to create a new top-level browsing context or reuse an existing top-level browsing context. If the user picks one of those options, then the designated browsing context must be the chosen one (the browsing context's name isn't set to the given browsing context name). The default behavior (if the user agent doesn't offer the option to the user, or if the user declines to allow a browsing context to be used) must be that there must not be a chosen browsing context.

    If this case occurs, it means that an author has explicitly sandboxed the document that is trying to open a link.

    If the user agent has been configured such that in this instance it will create a new browsing context:

    A new auxiliary browsing context must be created, with the opener browsing context being the current one. If the given browsing context name is not _blank, then the new auxiliary browsing context's name must be the given browsing context name (otherwise, it has no name). The chosen browsing context must be this new browsing context.

    If the newly created browsing context is immediately navigated, then the navigation will be done with replacement enabled.

    If the user agent has been configured such that in this instance it will reuse the current browsing context

    The chosen browsing context is the current browsing context.

    If the user agent has been configured such that in this instance it will not find a browsing context

    There must not be a chosen browsing context.

    User agent implementors are encouraged to provide a way for users to configure the user agent to always reuse the current browsing context.

    If the chosen browsing context picked above, if any, is a new browsing context, then:

    1. Let flagSet be the current browsing context's active document's active sandboxing flag set.

    2. If flagSet's sandboxed navigation browsing context flag is set, then the current browsing context must be set as the new browsing context's one permitted sandboxed navigator.

    3. If flagSet's sandbox propagates to auxiliary browsing contexts flag is set, then all the flags that are set in flagSet must be set in the new browsing context's popup sandboxing flag set.

7.1.6 Script settings for browsing contexts

When the user agent is required to set up a browsing context environment settings object, given a JavaScript execution context execution context and an optional environment reserved environment, it must run the following steps:

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

  2. Let window be realm's global object.

  3. Let url be a copy of the URL of window's associated Document.

  4. 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 responsible browsing context

    Return the browsing context with which window is associated.

    The responsible event loop

    Return the event loop that is associated with the unit of related similar-origin browsing contexts to which window's browsing context belongs.

    The responsible document

    Return 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 HTTPS state

    Return the HTTPS state of window's associated Document.

    The referrer policy
    1. Let document be the Document with which window is currently associated.

    2. While document is an iframe srcdoc document and document's referrer policy is the empty string, set document to document's browsing context's browsing context container's node document.

    3. Return document's referrer policy.

  5. If reserved environment is given, then:

    1. Set settings object's id to reserved environment's id, settings object's creation URL to reserved environment's creation URL, settings object's target browsing context to reserved environment's target browsing context, and settings object's active service worker to reserved environment's active service worker.

    2. Set reserved environment'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.

  6. Otherwise, set settings object's id to a new unique opaque string, settings object's creation URL to url, settings object's target browsing context to null, and settings object's active service worker to null.

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

  8. Return settings object.

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

7.2.1 Integration with IDL

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

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

    1. Repeat for each e that is an element 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.

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

7.2.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.3 Shared abstract operations

7.2.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. Let crossOriginWindowProperties be « { [[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" } ».

  4. Repeat for each e that is an element of O's document-tree child browsing context name property set:

    1. Add { [[Property]]: e } as the last element of crossOriginWindowProperties.

  5. Return crossOriginWindowProperties.

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

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

7.2.3.3 CrossOriginGetOwnPropertyHelper ( O, P )

If this abstract operation returns undefined and there is no custom behavior, the caller needs to throw a "SecurityError" DOMException.

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

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

  3. Repeat for each e that is an element 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 Record, 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 Record, 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 Record, 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.

  4. Return undefined.

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]

7.2.3.4 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, throw a "SecurityError" DOMException.

  7. Return ? Call(getter, Receiver).

7.2.3.5 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.3.6 CrossOriginOwnPropertyKeys ( O )
  1. Let keys be a new empty List.

  2. Repeat for each e that is an element of CrossOriginProperties(O):

    1. Add e.[[Property]] as the last element of keys.

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

7.3 Windowオブジェクト

[PrimaryGlobal, LegacyUnenumerableNamedProperties] 
interface Window : EventTarget {
  // the current browsing context
  [Unforgeable] readonly attribute WindowProxy window;
  [Replaceable] readonly attribute WindowProxy self;
  [Unforgeable] readonly attribute Document document;
  attribute DOMString name;
  [PutForwards=href, Unforgeable] 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;
  void close();
  readonly attribute boolean closed;
  void stop();
  void focus();
  void blur();

  // other browsing contexts
  [Replaceable] readonly attribute WindowProxy frames;
  [Replaceable] readonly attribute unsigned long length;
  [Unforgeable] readonly attribute WindowProxy?top;
  attribute any opener;
  [Replaceable] readonly attribute WindowProxy?parent;
  readonly attribute Element?frameElement;
  WindowProxy?open(optional USVString url = "about:blank", optional DOMString target = "_blank", [TreatNullAs=EmptyString] optional 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 ApplicationCache applicationCache;

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

  unsigned long requestAnimationFrame(FrameRequestCallback callback);
  void cancelAnimationFrame(unsigned long handle);

  void postMessage(any message, USVString targetOrigin, optional sequence<object> transfer = []);
};
Window implements GlobalEventHandlers;
Window implements WindowEventHandlers;

callback FrameRequestCallback = void (DOMHighResTimeStamp time);
window . window
window . frames
window . self

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

window . document

windowと関連するDocumentを返す。

document . defaultView

アクティブドキュメントWindowオブジェクトを返す。

The Window has an associated Document, which is a Document object. It is set when the Window object is created, and only ever changed during navigation from the initial about:blank Document.

The window, frames, and self IDL attributes, on getting, must all return this Window object's browsing context's WindowProxy object.

The document IDL attribute, on getting, must return this Window object's associated Document.

The Document object associated with a Window object can change in exactly one case: when the navigate algorithm initializes a new Document object for the first page loaded in a browsing context. In that specific case, the Window object of the original about:blank page is reused and gets a new Document object.

The defaultView IDL attribute of the Document interface, on getting, must return this Document's browsing context's WindowProxy object, if this Document has an associated browsing context, or null otherwise.


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

7.3.1 名前でブラウジングコンテキストを作成および操作するためのAPI

window = window . open( [ url [, target [, features ] ] ] )

url(デフォルトでabout:blank)を表示するためのウィンドウを開き、それを返す。target引数は、新しいウィンドウの名前を与える。すでにその名前をもつウィンドウが存在する場合、それが再利用される。features引数は、新しいウィンドウのレンダリングに影響を与えるために使用することができる。

window . name [ = value ]

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

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

window . close()

ウィンドウを閉じる。

window . closed

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

window . stop()

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

The open(url, target, features) method on Window objects provides a mechanism for navigating an existing browsing context or opening and navigating an auxiliary browsing context.

When the method is invoked, the user agent must run the following steps:

  1. Let entry settings be the entry settings object.

  2. Let source browsing context be the responsible browsing context specified by entry settings.

  3. If target is the empty string, let it be the string "_blank" instead.

  4. If the user has indicated a preference for which browsing context to navigate, follow these substeps:

    1. Let target browsing context be the browsing context indicated by the user.

    2. If target browsing context is a new top-level browsing context, let the source browsing context be set as target browsing context's one permitted sandboxed navigator.

    For example, suppose there is a user agent that supports control-clicking a link to open it in a new tab. If a user clicks in that user agent on an element whose onclick handler uses the window.open() API to open a page in an iframe, but, while doing so, holds the control key down, the user agent could override the selection of the target browsing context to instead target a new tab.

    Otherwise, apply the rules for choosing a browsing context given a browsing context name using target as the name and source browsing context as the context in which the algorithm is executed. If this results in there not being a chosen browsing context, then return null. Otherwise, let target browsing context be the browsing context so obtained.

  5. If target browsing context was just created, either as part of the rules for choosing a browsing context given a browsing context name or due to the user indicating a preference for navigating a new top-level browsing context, then let new be true. Otherwise, let it be false.

  6. Interpret features as defined in the CSSOM View specification. [CSSOMVIEW]

  7. If url is the empty string, run the appropriate steps from the following list:

    If new is false

    Jump to the step labeled end.

    If new is true

    Let resource be the URL "about:blank".

    Otherwise, parse url relative to entry settings, and let resource be the resulting URL record, if any. If the parse a URL algorithm failed, then run one of the following two steps instead:

  8. If resource is "about:blank" and new is true, then queue a task to fire an event named load at target browsing context's Window object, with legacy target override flag set.

    Otherwise, navigate target browsing context to resource, with the exceptions enabled flag set. If new is true, then replacement must be enabled. The source browsing context is source browsing context. 例外を再度投げる。

  9. End:

    1. If the result of splitting features on commas contains the token "noopener", then disown target browsing context's opener and return null.

    2. Otherwise, return the WindowProxy object of target browsing context.


The name attribute of the Window object must, on getting, return the current name of the browsing context; and, on setting, set the name of the browsing context to the new value.

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


The close() method on Window objects should, if all the following conditions are met, close the browsing context A:

A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a top-level browsing context whose session history contains only one Document.

The closed attribute on Window objects must return true if the Window object's browsing context has been discarded, and false otherwise.

The stop() method on Window objects should, if there is an existing attempt to navigate the browsing context and that attempt is not currently running the unload a document algorithm, cancel that navigation; then, it must abort the active document of the browsing context of the Window object on which it was invoked.

7.3.2 他のブラウジングコンテキストへのアクセス

window . length

文書ツリー子ブラウジングコンテキストの数を返す。

window[index]

指示された文書ツリー子ブラウジングコンテキストを返す。

The number of document-tree child browsing contexts of a Window object W is the number of document-tree child browsing contexts of W's associated Document's browsing context.

The length IDL attribute's getter must return the number of document-tree child browsing contexts of this Window object.

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

7.3.3 Windowオブジェクトの名前付きアクセス

window[name]

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

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

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

  1. Let activeDocument be window's browsing context's active document.

  2. Let childBrowsingContexts be all document-tree child browsing contexts of activeDocument's browsing context whose browsing context name is not the empty string, in order, and including only the first document-tree child browsing context with a given name if multiple document-tree child browsing contexts have the same one.

  3. Remove each browsing context from childBrowsingContexts whose active document's origin is not same origin with activeDocument's origin and whose browsing context name does not match the name of its browsing context container's name content attribute value.

  4. Return the browsing context names of childBrowsingContexts, in the same order.

This means that in the following example, hosted on https://example.org/, assuming https://elsewhere.example/ sets window.name to "spices", evaluating window.spices after everything has loaded will yield undefined:

<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, the user agent must return the value obtained using the following steps:

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

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

  2. If objects contains a nested browsing context, then return the WindowProxy object of the nested browsing context corresponding to the first browsing context container in tree order whose nested browsing context is in objects, and abort these steps.

  3. Otherwise, if objects has only one element, return that element and abort these steps.

  4. Otherwise return an HTMLCollection rooted at the Document node, whose filter matches only named objects with the name name. (By definition, these will all be elements.)

Named objects with the name name, for the purposes of the above algorithm, consist of the following:

7.3.4 Garbage collection and browsing contexts

A browsing context has a strong reference to each of its Documents and its WindowProxy object, and the user agent itself has a strong reference to its top-level browsing contexts.

A Document has a strong reference to its Window object.

A Window object has a strong reference to its Document object through its document attribute. Thus, references from other scripts to either of those objects will keep both alive. Similarly, both Document and Window objects have implied strong references to the WindowProxy object.

Each script has a strong reference to its settings object, and each environment settings object has strong references to its global object, responsible browsing context, and responsible document (if any).

When a browsing context is to discard a Document, the user agent must run the following steps:

  1. Set the Document's salvageable state to false.

  2. Run any unloading document cleanup steps for the Document that are defined by this specification and other applicable specifications.

  3. Abort the Document.

  4. Remove any tasks associated with the Document in any task source, without running those tasks.

  5. Discard all the child browsing contexts of the Document.

  6. Lose the strong reference from the Document's browsing context to the Document.

Whenever a Document object is discarded, it is also removed from the list of the worker's Documents of each worker whose list contains that Document.

When a browsing context is discarded, the strong reference from the user agent itself to the browsing context must be severed, and all the Document objects for all the entries in the browsing context's session history must be discarded as well.

User agents may discard top-level browsing contexts at any time (typically, in response to user requests, e.g. when a user force-closes a window containing one or more top-level browsing contexts). Other browsing contexts must be discarded once their WindowProxy object is eligible for garbage collection, in addition to the other places where this specification requires them to be discarded.

A WindowProxy does not have a strong reference to the browsing context it was created alongside. In particular, it is possible for a nested browsing context to be discarded even if JavaScript code holds a reference to its WindowProxy object.

7.3.5 ブラウジングコンテキストを閉じる

ユーザーエージェントは、ブラウジングコンテキストを閉じることを供給される場合、以下のステップを実行しなければならない:

  1. specified browsing contextを閉じられているブラウジングコンテキストとする。

  2. specified browsing contextアクティブなドキュメントアンロードするように要求する。ユーザーが文書をアンロードできるようにすることを拒否した場合、これらの手順を中止する。

  3. falseに設定するrecycleパラメーターをもつspecified browsing contextアクティブなドキュメントアンロードする

  4. ユーザーインターフェイス(たとえばタブブラウザーでタブを閉じる、または非表示にする)から、specified browsing contextを削除する。

  5. specified browsing context破棄する

ユーザーエージェントは、ユーザーが任意に任意のトップレベルブラウジングコンテキスト閉じる機能を提供すべきである。

7.3.6 ブラウザーインターフェイス要素

ウェブページがウェブブラウザーと統合できるようにするために、特定のウェブブラウザーインターフェイス要素はウェブページ内のスクリプトに限られた方法で公開される。

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

interface BarProp {
  readonly attribute boolean visible;
};
window . locationbar . visible

ロケーションバーが表示される場合はtrueを返し、そうでなければfalseを返す。

window . menubar . visible

メニューバーが表示される場合はtrueを返し、そうでなければfalseを返す。

window . personalbar . visible

パーソナルバーが表示される場合はtrueを返し、そうでなければfalseを返す。

window . scrollbars . visible

スクロールバーが表示される場合はtrueを返し、そうでなければfalseを返す。

window . statusbar . visible

ステータスバーが表示される場合はtrueを返し、そうでなければfalseを返す。

window . toolbar . visible

ツールバーが表示される場合はtrueを返し、そうでなければfalseを返す。

The visible attribute, on getting, must return either true or a value determined by the user agent to most accurately represent the visibility state of the user interface element that the object represents, as described below.

The following BarProp objects exist for each Document object in a browsing context. Some of the user interface elements represented by these objects might have no equivalent in some user agents; for those user agents, except when otherwise specified, the object must act as if it was present and visible (i.e. its visible attribute must return true).

The location bar BarProp object
Represents the user interface element that contains a control that displays the URL of the active document, or some similar interface concept.
The menu bar BarProp object
Represents the user interface element that contains a list of commands in menu form, or some similar interface concept.
The personal bar BarProp object
Represents the user interface element that contains links to the user's favorite pages, or some similar interface concept.
The scrollbar BarProp object
Represents the user interface element that contains a scrolling mechanism, or some similar interface concept.
The status bar BarProp object
Represents a user interface element found immediately below or after the document, as appropriate for the user's media, which typically provides information about ongoing network activity or information about elements that the user's pointing device is current indicating. If the user agent has no such user interface element, then the object may act as if the corresponding user interface element was absent (i.e. its visible attribute may return false).
The toolbar BarProp object
Represents the user interface element found immediately above or before the document, as appropriate for the user's media, which typically provides session history traversal controls (back and forward buttons, reload buttons, etc). If the user agent has no such user interface element, then the object may act as if the corresponding user interface element was absent (i.e. its visible attribute may return false).

The locationbar attribute must return the location bar BarProp object.

The menubar attribute must return the menu bar BarProp object.

The personalbar attribute must return the personal bar BarProp object.

The scrollbars attribute must return the scrollbar BarProp object.

The statusbar attribute must return the status bar BarProp object.

The toolbar attribute must return the toolbar BarProp object.


For historical reasons, the status attribute on the Window object must, on getting, return the last string it was set to, and on setting, must set itself to the new value. When the Window object is created, the attribute must be set to the empty string. It does not do anything else.

7.4 The WindowProxy exotic object

A WindowProxy is an exotic object that wraps a Window ordinary object, indirecting most operations through to the wrapped object. Each browsing context has an associated WindowProxy object. When the browsing context is navigated, the Window object wrapped by the browsing context's associated WindowProxy object is changed.

There is no WindowProxy interface object.

Every WindowProxy object has a [[Window]] internal slot representing the wrapped Window object.

The WindowProxy object internal methods are described in the subsections below.

Although WindowProxy is named as a "proxy", it does not do polymorphic dispatch on its target's internal methods as a real proxy would, due to a desire to reuse machinery between WindowProxy and Location objects. As long as the Window object remains an ordinary object this is unobservable and can be implemented either way.

7.4.1 [[GetPrototypeOf]] ( )

  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.4.2 [[SetPrototypeOf]] ( V )

  1. Return false.

7.4.3 [[IsExtensible]] ( )

  1. Return true.

7.4.4 [[PreventExtensions]] ( )

  1. Return false.

7.4.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 maxProperties be the number of document-tree child browsing contexts of W.

    3. Let value be undefined.

    4. If maxProperties is greater than 0 and index is less than maxProperties, then:

      1. Let document be W's associated Document.

      2. Set value to the WindowProxy object of the indexth document-tree child browsing context of document's browsing context, sorted in the order that their browsing context container elements were most recently inserted into document, the WindowProxy object of the most recently inserted browsing context container's nested browsing context being last.

    5. Return PropertyDescriptor{ [[Value]]: value, [[Writable]]: false, [[Enumerable]]: false, [[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, return property.

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

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

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

  7. Throw a "SecurityError" DOMException.

7.4.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.4.7 [[Get]] ( P, Receiver )

  1. Let W be the value of the [[Window]] internal slot of this.

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

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

7.4.8 [[Set]] ( P, V, Receiver )

  1. Let W be the value of the [[Window]] internal slot of this.

  2. If IsPlatformObjectSameOrigin(W) is true, then return ? OrdinarySet(W, this, Receiver).

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

7.4.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 return false.

    2. Return ? OrdinaryDelete(W, P).

  3. Throw a "SecurityError" DOMException.

7.4.10 [[OwnPropertyKeys]] ( )

  1. Let W be the value of the [[Window]] internal slot of this.

  2. Let keys be a new empty List.

  3. Let maxProperties be the number of document-tree child browsing contexts of W.

  4. indexを0にする。

  5. Repeat while index < maxProperties,

    1. Add ! ToString(index) as the last element of keys.

    2. Increment index by 1.

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

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

7.5 生成元

Spec bugs: 28374

生成元は、ウェブのセキュリティーモデルの基本的な通貨である。生成元を共有するウェブプラットフォーム内の2つの当事者が互いに信頼し、同一の権限を有すると仮定される。異なる生成元をもつ当事者は、互いに潜在的に悪意があると見なされ、互いから程度を変化させるよう隔離される。

For example, if Example Bank's Web site, hosted at bank.example.com, tries to examine the DOM of Example Charity's Web site, hosted at charity.example.org, a "SecurityError" DOMException will be raised.


An origin is one of the following:

An opaque origin

An internal value, with no serialization it can be recreated from (it is serialized as "null" per ASCII serialization of an origin), for which the only meaningful operation is testing for equality.

A tuple origin

A tuple consists of:

Origins can be shared, e.g., among multiple Document objects. Furthermore, origins are generally immutable. Only the domain of a tuple origin can be changed, and only through the document.domain API.

The effective domain of an origin origin is computed as follows:

  1. If origin is an opaque origin, then return null.

  2. If origin's domain is non-null, then return origin's domain.

  3. Return origin's host.

Various specification objects are defined to have an origin. These origins are determined as follows:

For Document objects
If the Document's active sandboxing flag set has its sandboxed origin browsing context flag set
If the Document was generated from a data: URL

A unique opaque origin assigned when the Document is created.

If the Document's URL's scheme is a network scheme

A copy of the Document's URL's origin assigned when the Document is created.

The document.open() method can change the Document's URL to "about:blank". Therefore the origin is assigned when the Document is created.

If the Document is the initial "about:blank" document

The one it was assigned when its browsing context was created.

If the Document is a non-initial "about:blank" document

The origin of the incumbent settings object when the navigate algorithm was invoked, or, if no script was involved, the origin of the node document of the element that initiated the navigation to that URL.

If the Document was created as part of the processing for javascript: URLs

The origin of the active document of the browsing context being navigated when the navigate algorithm was invoked.

If the Document is an iframe srcdoc document

The origin of the Document's browsing context's browsing context container's node document.

If the Document was obtained in some other manner (e.g. a Document created using the createDocument() API, etc)

The default behavior as defined in the WHATWG DOM standard applies. [DOM].

The origin is a unique opaque origin assigned when the Document is created.

For images of img elements
If the image data is CORS-cross-origin

A unique opaque origin assigned when the image is created.

If the image data is CORS-same-origin

The img element's node document's origin.

For audio and video elements
If the media data is CORS-cross-origin

A unique opaque origin assigned when the media data is fetched.

If the media data is CORS-same-origin

The media element's node document's origin.

Other specifications can override the above definitions by themselves specifying the origin of a particular Document object, image, or media element.


The Unicode serialization of an origin is the string obtained by applying the following algorithm to the given origin origin:

  1. If origin is an opaque origin, then return "null".

  2. Let host be origin's host.

  3. Let unicodeHost be host if host is not a domain, and the result of applying domain to Unicode to host otherwise.

  4. Let unicodeOrigin be a new tuple origin consisting origin's scheme, unicodeHost, and origin's port.

  5. Return the ASCII serialization of an origin, given unicodeOrigin.

    The name ASCII serialization of an origin is misleading, as it merely serializes an origin, which are all ASCII by default due to the URL parser.

The Unicode serialization of ("https", "xn--maraa-rta.example", null, null) is "https://maraña.example".

The ASCII serialization of an origin is the string obtained by applying the following algorithm to the given origin origin:

  1. If origin is an opaque origin, then return "null".

  2. Otherwise, let result be origin's scheme.

  3. Append "://" to result.

  4. Append origin's host, serialized, to result.

  5. If origin's port is non-null, append a U+003A COLON character (:), and origin's port, serialized, to result.

  6. Return result.


Two origins, A and B, are said to be same origin if the following algorithm returns true:

  1. If A and B are the same opaque origin, then return true.

  2. If A and B are both tuple origins and their schemes, hosts, and port are identical, then return true.

  3. Return false.

Two origins, A and B, are said to be same origin-domain if the following algorithm returns true:

  1. If A and B are the same opaque origin, then return true.

  2. If A and B are both tuple origins, run these substeps:

    1. If A and B's schemes are identical, and their domains are identical and non-null, then return true.

    2. Otherwise, if A and B are same origin and their domains are identical and null, then return true.

  3. Return false.

A B same origin same origin-domain
("https", "example.org", null, null) ("https", "example.org", null, null)
("https", "example.org", 314, null) ("https", "example.org", 420, null)
("https", "example.org", 314, "example.org") ("https", "example.org", 420, "example.org")
("https", "example.org", null, null) ("https", "example.org", null, "example.org")
("https", "example.org", null, "example.org") ("http", "example.org", null, "example.org")

7.5.1 同一生成元制限を緩和する

document . domain [ = domain ]

セキュリティーチェックのために使用される現在のドメインを返す。

Can be set to a value that removes subdomains, to change the origin's domain to allow pages on other subdomains of the same domain (if they do the same thing) to access each other. (Can't be set in sandboxed iframes.)

To determine if a string hostSuffixString is a registrable domain suffix of or is equal to a host originalHost, run these steps:

  1. If hostSuffixString is the empty string, then return false.

  2. Let host be the result of parsing hostSuffixString.

  3. If host is failure, then return false.

  4. If host is not equal to originalHost, then run these substeps:

    1. If host or originalHost is not a domain, then return false.

      This is meant to exclude hosts that are an IPv4 address or an IPv6 address.

    2. If host, prefixed by a U+002E FULL STOP (.), does not exactly match the end of originalHost, then return false.

    3. If host matches a suffix in the Public Suffix List, or, if host, prefixed by a U+002E FULL STOP (.), matches the end of a suffix in the Public Suffix List, then return false. [PSL]

      Suffixes must be compared after applying the host parser algorithm.

  5. Return true.

The domain attribute's getter must run these steps:

  1. If this Document object does not have a browsing context, then return the empty string.

  2. Let effectiveDomain be this Document's origin's effective domain.

  3. If effectiveDomain is null, then return the empty string.

  4. Return effectiveDomain, serialized.

The domain attribute's setter must run these steps:

  1. If this Document object has no browsing context, then throw a "SecurityError" DOMException.

  2. If this Document object's active sandboxing flag set has its sandboxed document.domain browsing context flag set, then throw a "SecurityError" DOMException.

  3. Let effectiveDomain be this Document's origin's effective domain.

  4. If effectiveDomain is null, then throw a "SecurityError" DOMException.

  5. If the given value is not a registrable domain suffix of and is not equal to effectiveDomain, then throw a "SecurityError" DOMException.

  6. Set this Document object's origin's domain to the result of parsing the given value.

The document.domain attribute is used to enable pages on different hosts of a domain to access each other's DOMs.

共有ホスティングを使用する際document.domainの属性を使用しない。信頼できない第三者が同じIPアドレスだが別のポート上でHTTPサーバーをホストできる場合、document.domain属性が使用された後に生成元を比較する際にポートは無視されるように、通常同じホスト上の2つの異なるサイトを保護する同一生成元の保護は失敗するだろう。

7.6 サンドボックス

サンドボックスフラグ設定は、潜在的に信頼されないリソースが持つ能力を制限するために使用される、以下のフラグに属するゼロ個以上のセットである:

サンドボックス化されたナビゲーションブラウジングコンテキストフラグ

This flag prevents content from navigating browsing contexts other than the sandboxed browsing context itself (or browsing contexts further nested inside it), auxiliary browsing contexts (which are protected by the sandboxed auxiliary navigation browsing context flag defined next), and the top-level browsing context (which is protected by the sandboxed top-level navigation without user activation browsing context flag and sandboxed top-level navigation with user activation browsing context flag defined below).

サンドボックス化された補助ナビゲーションブラウジングコンテキストフラグが設定されない場合、それにもかかわらず一定の場合における制限はポップアップ(新しいトップレベルブラウジングコンテキスト)を開くことができる。これらのブラウジングコンテキストは常に、1つの許可されたサンドボックス化されたナビゲーターを持ち、実際に移動するために作成したブラウジングコンテキストを許可する、ブラウジングコンテキストが作成される際に設定を持つ。(そうでなければ、サンドボックス化されたナビゲーションブラウジングコンテキストフラグは、それらが開かれた場合であってもナビゲートされていくのを防ぐだろう。)

サンドボックス化された補助ナビゲーションブラウジングコンテキストフラグ

This flag prevents content from creating new auxiliary browsing contexts, e.g. using the target attribute or the window.open() method.

The sandboxed top-level navigation without user activation browsing context flag

このフラグは、それらのトップレベルブラウジングコンテキストのナビゲートからコンテンツを防ぎ、かつそれらのトップレベルブラウジングコンテキストの遮断からコンテンツを防ぐ。It is consulted only from algorithms that are not triggered by user activation.

When the sandboxed top-level navigation without user activation browsing context flag is not set, content can navigate its top-level browsing context, but other browsing contexts are still protected by the sandboxed navigation browsing context flag and possibly the sandboxed auxiliary navigation browsing context flag.

The sandboxed top-level navigation with user activation browsing context flag

このフラグは、それらのトップレベルブラウジングコンテキストのナビゲートからコンテンツを防ぎ、かつそれらのトップレベルブラウジングコンテキストの遮断からコンテンツを防ぐ。It is consulted only from algorithms that are triggered by user activation.

As with the sandboxed top-level navigation without user activation browsing context flag, this flag only affects the top-level browsing context; if it is not set, other browsing contexts might still be protected by other flags.

サンドボックス化されたプラグインブラウジングコンテキストフラグ

これらのプラグイン安全でない限り、embed要素object要素applet要素を使用しているかどうか、またはネストされたブラウジングコンテキストナビゲーションを介して、このフラグは、プラグインをインスタンス化するコンテンツを防ぐ。

サンドボックス化された生成元ブラウジングコンテキストフラグ

このフラグは、一意な生成元にコンテンツを強制する。したがって、同一生成元から他のコンテンツにアクセスすることを防止する。

このフラグはまた、document.cookie IDL属性からの読み取りまたは書き込みをするスクリプトを防止しlocalStorageへのアクセスをブロックする。

サンドボックス化されたフォームブラウジングコンテキストフラグ

このフラグはフォーム送信をブロックする

サンドボックス化されたポインターロックブラウジングコンテキストフラグ

このフラグはPointer Lock APIを無効にする。[POINTERLOCK]

サンドボックス化されたスクリプトブラウジングコンテキストフラグ

このフラグは、スクリプトの実行をブロックする

サンドボックス化された自動機能ブラウジングコンテキストフラグ

このフラグは、自動ビデオ再生自動フォームコントロールフォーカスなどの、自動的に切り替える機能をブロックする。

The sandboxed storage area URLs flag

This flag prevents URL schemes that use storage areas from being able to access the origin's data.

サンドボックス化されたdocument.domainブラウジングコンテキストフラグ

This flag prevents content from using the document.domain setter.

The sandbox propagates to auxiliary browsing contexts flag

This flag prevents content from escaping the sandbox by ensuring that any auxiliary browsing context it creates inherits the content's active sandboxing flag set.

The sandboxed modals flag

This flag prevents content from using any of the following features to produce modal dialogs:

The sandboxed orientation lock browsing context flag

This flag disables the ability to lock the screen orientation. [SCREENORIENTATION]

The sandboxed presentation browsing context flag

This flag disables the Presentation API. [PRESENTATION]

When the user agent is to parse a sandboxing directive, given a string input, a sandboxing flag set output, it must run the following steps:

  1. Split input on ASCII whitespace, to obtain tokens.

  2. outputを空にする。

  3. outputに次のフラグを追加する:


すべてのトップレベルブラウジングコンテキストは、サンドボックスフラグが設定される、ポップアップサンドボックスフラグ設定を持つ。ブラウジングコンテキストが作成される場合、そのポップアップサンドフラグ設定は空でなければならない。これは、ブラウジングコンテキスト名を指定されるブラウジングコンテキストを選択するための規則によって移入される。

Every browsing context that is a nested browsing context has an iframe sandboxing flag set, which is a sandboxing flag set. Which flags in a nested browsing context's iframe sandboxing flag set are set at any particular time is determined by the iframe element's sandbox attribute.

すべてのDocumentは、サンドボックスフラグ設定である、アクティブサンドボックスフラグ設定を持つ。Documentが作成される場合、そのアクティブサンドボックスフラグ設定が空でなければならない。それは、ナビゲーションアルゴリズムによって追加される。

ナビゲーションアルゴリズムによって得られるすべてのリソースは、サンドボックスフラグが設定される、強制サンドボックスフラグ設定を持つ。デフォルトでリソースは、その強制サンドボックスフラグセットで設定されるフラグを持たないが、他の仕様は、特定のフラグが設定されていることを定義できる。

具体的には、強制サンドボックスフラグセットContent Security Policyによって使用される。[CSP]


To implement the sandboxing for a Document object document, populate document's active sandboxing flag set with the union of the flags that are present in the following sandboxing flag sets:

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

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

ブラウジングコンテキスト内のDocumentの配列は、そのセッション履歴である。ネストされたブラウジングコンテキストを含む各ブラウジングコンテキストは、個別のセッション履歴を持つ。ブラウジングコンテキストのセッション履歴は、セッション履歴のエントリのフラットなリストから成る。Each session history entry consists, at a minimum, of a URL, and each entry may in addition have a state object, a title, a Document object, form data, a scroll restoration mode, a scroll position, a browsing context name, and other information associated with it.

最初に作成される際、各エントリはDocumentを持つ。しかし、Document活性化でない場合、リソースを解放するために廃棄することができる。The URL and other data in a session history entry is then used to bring a new Document into being to take the place of the original, in case the user agent finds itself having to reactivate that Document.

セッション履歴エントリに関連付けられたタイトルは、Documentの現在のtitleと関係をもつ必要はない。セッション履歴エントリのタイトルは、ユーザーが文書の履歴をナビゲートできるように、その時点で文書の状態を説明しようとするものである。

セッション履歴関連付けられるURLが、ユーザー(またはスクリプト)がページからページへ移動するように状態に追加される。


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

The history attribute of the Window interface must return the object implementing the History interface for this Window object's associated Document.


状態オブジェクトは、ユーザーインターフェイスの状態を表すオブジェクトである。

ページは、セッション履歴に状態オブジェクト追加できる。このように著者に一つでもページのアプリケーションでは"ナビゲーション"メタファーを使用できるように、これらは、ユーザー(またはスクリプト)が履歴に戻る際にその後スクリプトに返される

状態オブジェクトは、2つの主な目的に使用されることを意図される:1つ目は、(それがユーザーによって扱うURLを渡されるものに対して解析する必要が依然としてあるので、マイナー最適化のみであるが)単純なケース場合において、著者が解析を行う必要がないように、URL内の状態の事前解析された説明を格納し、2つ目は、新しいDocumentが開かれた場合、現在のDocumentインスタンスのみに適用され、再構築しなければならないため、著者はそれがURLに格納しない状態を保存できるようにする。

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


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

The current entry is usually an entry for the URL of the Document. しかし、それはまた、その文書によって履歴に追加された状態オブジェクトのエントリのいずれかを指定できる。

永続ユーザー状態を持つエントリはまた、ユーザーエージェント定義の状態を持つ。この仕様は、何が状態の種類を格納できるのかを指定しない。

たとえば、一部のユーザーエージェントは、スクロール位置またはフォームコントロールの値を永続化したいかもしれない。

フォームコントロールの値を永続化するユーザーエージェントはまた、それらの方向(要素のdir属性の値)を保持することが推奨される。これは、ユーザーが最初明示的にデフォルト以外の方向をもつ値を入力した場合、履歴走査の後に誤って値を表示することを防ぐ。

An entry's scroll restoration mode indicates whether the user agent should restore the persisted scroll position (if any) when traversing to it. The scroll restoration mode may be one of the following:

"auto"
The user agent is responsible for restoring the scroll position upon navigation.
"manual"
The page is responsible for restoring the scroll position and the user agent does not attempt to do so automatically

If unspecified, the scroll restoration mode of a new entry must be set to "auto".

状態オブジェクトから成るエントリは、追加された際にアクティブであったページのエントリと同じDocumentを共有する。

Contiguous entries that differ just by their URLs' fragments also share the same Document.

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

ブラウジングコンテキスト内の各Documentはまた、最新のエントリを持つことができる。This is the entry for that Document to which the browsing context's session history was most recently traversed. When a Document is created, it initially has no latest entry.

User agents may discard the Document objects of entries other than the current entry that are not referenced from any script, reloading the pages afresh when the user or script navigates back to such pages. This specification does not specify when user agents should discard Document objects and when they should cache them.

Entries that have had their Document objects discarded must, for the purposes of the algorithms given below, act as if they had not. When the user or script navigates back or forwards to a page which has no in-memory DOM objects, any other entries that shared the same Document object with it must share the new object as well.

7.7.2 Historyインターフェイス

enum ScrollRestoration { "auto", "manual" };

interface History {
  readonly attribute unsigned long length;
  attribute ScrollRestoration scrollRestoration;
  readonly attribute any state;
  void go(optional long delta = 0);
  void back();
  void forward();
  void pushState(any data, DOMString title, optional USVString? url = null);
  void replaceState(any data, DOMString title, optional USVString? url = null);
};
window . history . length

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

window . history . scrollRestoration [ = value ]

Returns the scroll restoration mode of the current entry in the session history.

Can be set, to change the scroll restoration mode of the current entry in the session history.

window . history . state

現在の状態オブジェクトを返す。

window . history . go( [ delta ] )

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

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

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

window . history . back()

ジョイントセッション履歴内の1つのステップに戻る。

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

window . history . forward()

ジョイントセッション履歴内の1つのステップに進む。

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

window . history . pushState(data, title [, url ] )

指定されたURLが供給される場合、指定されたタイトルとともに、セッション履歴上に与えられたデータをプッシュする。

window . history . replaceState(data, title [, url ] )

指定されたデータ、タイトルおよび、提供される場合にURLを持つ、セッション履歴の現在のエントリを更新する。

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

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

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

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

The length attribute of the History interface, on getting, must return the number of entries in the top-level browsing context's joint session history. If this History object is associated with a Document that is not fully active, getting must instead throw a "SecurityError" DOMException.

The actual entries are not accessible from script.

The scrollRestoration attribute of the History interface, on getting, must return the scroll restoration mode of the current entry in the session history. On setting, the scroll restoration mode of the current entry in the session history must be set to the new value. If this History object is associated with a Document that is not fully active, both getting and setting must instead throw a "SecurityError" DOMException.

The state attribute of the History interface, on getting, must return the last value it was set to by the user agent. If this History object is associated with a Document that is not fully active, getting must instead throw a "SecurityError" DOMException. Initially, its value must be null.

When the go(delta) method is invoked, if delta is zero, the user agent must act as if the location.reload() method was called instead. Otherwise, the user agent must traverse the history by a delta whose value is delta. If this History object is associated with a Document that is not fully active, invoking must instead throw a "SecurityError" DOMException.

When the back() method is invoked, the user agent must traverse the history by a delta −1. If this History object is associated with a Document that is not fully active, invoking must instead throw a "SecurityError" DOMException.

When the forward() method is invoked, the user agent must traverse the history by a delta +1. If this History object is associated with a Document that is not fully active, invoking must instead throw a "SecurityError" DOMException.


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 agent has more than one event loop per unit of related browsing contexts), transitions would otherwise have to involve cross-event-loop synchronization.


To traverse the history by a delta delta, 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 abort these steps.

  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 the specified browsing context's active document's unload a document algorithm is currently running, abort these steps.

  5. Queue a task that consists of running the following substeps. The relevant event loop is that of the specified browsing context's active document. The task source for the queued task is the history traversal task source.

    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. specified browsing contextアクティブなドキュメントアンロードするように要求する。ユーザーが文書をアンロードできるようにすることを拒否した場合、これらの手順を中止する。

      2. falseに設定するrecycleパラメーターをもつspecified browsing contextアクティブなドキュメントアンロードする

    3. Traverse the history of the specified browsing context to the specified entry.

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 equivalent to the action specified by the user.


The pushState(data, title, url) method adds a state object entry to the history.

Support: historyChrome for Android 56+Chrome 5+iOS Safari 5.0+UC Browser for Android (limited) 11+Firefox 4+IE 10+Samsung Internet 4+Opera Mini NoneAndroid Browser 4.2+Safari 6+Edge 12+Opera 11.5+

Source: caniuse.com

The replaceState(data, title, url) method updates the state object, title, and optionally the URL of the current entry in the history.

When either of these methods is invoked, the user agent must run the following steps:

  1. Let document be the unique Document object this History object is associated with.

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

  3. Optionally, abort these steps. (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 targetRealm be this History object's relevant Realm.

  5. Let cloned data be StructuredClone(data, targetRealm). 例外を再度投げる。

  6. If the third argument is not null, run these substeps:

    1. Parse the value of the third argument, relative to the relevant settings object of this History object.
    2. If that fails, throw a "SecurityError" DOMException and abort these steps.
    3. Let new URL be the resulting URL record.

    4. Compare new URL to document's URL. If any component of these two URL records differ other than the path, query, and fragment components, then throw a "SecurityError" DOMException and abort these steps.
    5. If the origin of new URL is not same origin with the origin of document, and either the path or query components of the two URL records compared in the previous step differ, throw a "SecurityError" DOMException and abort these steps. (This prevents sandboxed content from spoofing other pages on the same origin.)
  7. If the third argument is null, then let new URL be the URL of the current entry.

  8. If the method invoked was the pushState() method:

    1. Remove all the entries in the browsing context'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. If appropriate, update the current entry to reflect any state that the user agent wishes to persist. The entry is then said to be an entry with persisted user state.

    4. Add a state object entry to the session history, after the current entry, with cloned data as the state object, the given title as the title, new URL as the URL of the entry, and the scroll restoration mode of the current entry in the session history as the scroll restoration mode.

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

    Otherwise, if the method invoked was the replaceState() method:

    1. Update the current entry in the session history so that cloned data is the entry's new state object, the given title is the new title, and new URL is the entry's new URL.

  9. If the current entry in the session history represents a non-GET request (e.g. it was the result of a POST submission) then update it to instead represent a GET request.

  10. Set document's URL to new URL.

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

  11. Set history.state to StructuredClone(cloned data, targetRealm).

  12. Set the current entry's Document object's latest entry to the current entry.

The title is purely advisory. User agents might use the title in the user interface.

User agents may limit the number of state objects added to the session history per page. If a page hits the UA-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.)

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

そのようなゲームで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, document.title, '?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にユーザーが移動するたびに解析する必要はないので、より便利な形式となる。

アプリケーションは、その時点で文書のtitle要素の値としてセッション履歴エントリの同じタイトルを使用しないかもしれない。たとえば、これはtitle要素内のブロックを示す単純なページである。明らかに、後方に以前の状態に移動する際にユーザーは時間内に戻らず、したがって、セッション履歴のタイトルに時間を置くことは不適切だろう。

<!DOCTYPE HTML>
<HTML LANG=EN>
<TITLE>Line</TITLE>
<SCRIPT>
 setInterval(function () { document.title = 'Line - ' + new Date(); }, 1000);
 var i = 1;
 function inc() {
   set(i+1);
   history.pushState(i, 'Line - ' + i);
 }
 function set(newI) {
   i = newI;
   document.forms.F.I.value = newI;
 }
</SCRIPT>
<BODY ONPOPSTATE="set(event.state)">
<FORM NAME=F>
State: <OUTPUT NAME=I>1</OUTPUT> <INPUT VALUE="Increment" TYPE=BUTTON ONCLICK="inc()">
</FORM>

Most applications want to use the same scroll restoration mode value for all of their history entries. To achieve this they can set the scrollRestoration attribute as soon as possible (e.g., in the first script element in the document's head element) to ensure that any entry added to the history session gets the desired scroll restoration mode.

<head>
  <script>
       if ('scrollRestoration' in history)
            history.scrollRestoration = 'manual';
  </script>
</head>
   

7.7.3 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.7.4 Locationインターフェイス

Each Window object is associated with a unique instance of a Location object, allocated when the Window object is created.

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. Perform ! location.[[DefineOwnProperty]]("valueOf", { [[Value]]: %ObjProto_valueOf%, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).

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

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

  5. 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 [Unforgeable], 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 [Unforgeable] 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 attribute's getter must return this Document object's relevant global object's Location object, if this Document object is fully active, and null otherwise.

The Window object's location attribute's getter must return this Window object'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.

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

  [Unforgeable] void assign(USVString url);
  [Unforgeable] void replace(USVString url);
  [Unforgeable] void reload();

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

Returns the Location object's URL.

Can be set, to navigate to the given URL.

location . origin

Returns the Location object's URL's origin.

location . protocol

Returns the Location object's URL's scheme.

Can be set, to navigate to the same URL with a changed scheme.

location . host

Returns the Location object's URL's host and port (if different from the default port for the scheme).

Can be set, to navigate to the same URL with a changed host and port.

location . hostname

Returns the Location object's URL's host.

Can be set, to navigate to the same URL with a changed host.

location . port

Returns the Location object's URL's port.

Can be set, to navigate to the same URL with a changed port.

location . pathname

Returns the Location object's URL's path.

Can be set, to navigate to the same URL with a changed path.

location . search

Returns the Location object's URL's query (includes leading "?" if non-empty).

Can be set, to navigate to the same URL with a changed query (ignores leading "?").

location . hash

Returns the Location object's URL's fragment (includes leading "#" if non-empty).

Can be set, to navigate to the same URL with a changed fragment (ignores leading "#").

location . assign(url)

Navigates to the given URL.

location . replace(url)

Removes the current page from the session history and navigates to the given URL.

location . reload()

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

location . ancestorOrigins

Returns a DOMStringList object listing the origins of the ancestor browsing contexts, from the parent browsing context to the top-level browsing context.

A Location object has an associated relevant Document, which is this Location object's associated Document object's browsing context's active document.

A Location object has an associated url, which is this Location object's relevant Document's URL.

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 Unicode serialization of current's active document's origin to output.

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

  7. End: Return output.

A Location object has an associated Location-object-setter navigate algorithm, which given a url, runs these steps:

  1. If any of the following conditions are met, let replacement flag be unset; otherwise, let it be set:

  2. Location-object navigate, given url and replacement flag.

To Location-object navigate, given a url and replacement flag, run these steps:

  1. The source browsing context is the responsible browsing context specified by the incumbent settings object.

  2. Navigate the browsing context to url, with the exceptions enabled flag set. 例外を再度投げる。

    If the replacement flag is set or the browsing context's session history contains only one Document, and that was the about:blank Document created when the browsing context was created, then the navigation must be done with replacement enabled.

The href attribute's getter must run these steps:

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

  2. Return this Location object's url, serialized.

The href attribute's setter must run these steps:

  1. Parse the given value relative to the entry settings object. If that failed, throw a TypeError exception.

  2. Location-object-setter navigate to the resulting URL record.

The href attribute setter intentionally has no security check.

The origin attribute's getter must run these steps:

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

  2. Return the Unicode serialization of this Location object's url's origin.

It returns the Unicode rather than the ASCII serialization for compatibility with MessageEvent.

The protocol attribute's getter must run these steps:

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

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

The protocol attribute's setter must run these steps:

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

  2. Let copyURL be a copy of this Location object's url.

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

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

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

  6. Location-object-setter navigate to copyURL.

The host attribute's getter must run these steps:

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

  2. Let url be this Location object'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 attribute's setter must run these steps:

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

  2. Let copyURL be a copy of this Location object's url.

  3. If copyURL's cannot-be-a-base-URL flag is set, terminate these steps.

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

  5. Location-object-setter navigate to copyURL.

The hostname attribute's getter must run these steps:

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

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

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

The hostname attribute's setter must run these steps:

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

  2. Let copyURL be a copy of this Location object's url.

  3. If copyURL's cannot-be-a-base-URL flag is set, terminate these steps.

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

  5. Location-object-setter navigate to copyURL.

The port attribute's getter must run these steps:

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

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

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

The port attribute's setter must run these steps:

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

  2. Let copyURL be a copy of this Location object's url.

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

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

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

  6. Location-object-setter navigate to copyURL.

The pathname attribute's getter must run these steps:

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

  2. Let url be this Location object's url.

  3. If url's cannot-be-a-base-URL flag is set, return the first string in url's path.

  4. If url's path is empty, then return the empty string.

  5. Return "/", followed by the strings in url's path (including empty strings), separated from each other by "/".

The pathname attribute's setter must run these steps:

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

  2. Let copyURL be a copy of this Location object's url.

  3. If copyURL's cannot-be-a-base-URL flag is set, terminate these steps.

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

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

  6. Location-object-setter navigate to copyURL.

The search attribute's getter must run these steps:

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

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

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

The search attribute's setter must run these steps:

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

  2. Let copyURL be a copy of this Location object's url.

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

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

    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, and the relevant Document's document's character encoding as encoding override.

  5. Location-object-setter navigate to copyURL.

The hash attribute's getter must run these steps:

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

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

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

The hash attribute's setter must run these steps:

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

  2. Let copyURL be a copy of this Location object's url.

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

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

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

  6. Location-object-setter navigate to copyURL.

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


When the assign(url) method is invoked, the user agent must run the following steps:

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

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

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

When the replace(url) method is invoked, the user agent must run the following steps:

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

  2. Location-object navigate to the resulting URL record with the replacement flag set.

The replace() method intentionally has no security check.

When the reload() method is invoked, the user agent must run the appropriate steps from the following list:

If this Location object'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 abort these steps.

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

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

If the browsing context's active document has its reload override flag set

Perform an overridden reload, with the browsing context being navigated as the responsible browsing context. 例外を再度投げる。

そうでなければ

Navigate the browsing context to this Location object's relevant Document's URL to perform an entry update of the browsing context's current entry, with the exceptions enabled flag set. The source browsing context must be the browsing context being navigated. This is a reload-triggered navigation. 例外を再度投げる。

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, to perform an entry update of the browsing context's current entry. This is a reload-triggered navigation. 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. If browsing context's active document's reload override flag is set, then the user agent may instead perform an overridden reload rather than the navigation described in this paragraph (with the browsing context being reloaded as the source browsing context).


The ancestorOrigins attribute's getter must run these steps:

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

  2. Otherwise, return this Location object's ancestor origins list.


As explained earlier, the Location exotic object requires additional logic beyond IDL for security purposes. The internal slot and internal methods Location objects must implement are defined below.

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

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

  2. Return null.

7.7.4.2 [[SetPrototypeOf]] ( V )
  1. Return false.

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

7.7.4.4 [[PreventExtensions]] ( )
  1. Return false.

7.7.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, return property.

  4. Throw a "SecurityError" DOMException.

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

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

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

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

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

  2. Throw a "SecurityError" DOMException.

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

  2. Return ! CrossOriginOwnPropertyKeys(this).

7.8 ウェブを閲覧する

Certain actions cause the browsing context to navigate to a new resource. A user agent may provide various ways for the user to explicitly cause a browsing context to navigate, in addition to those defined in this specification.

For example, following a hyperlink, form submission, and the window.open() and location.assign() methods can all cause a browsing context to navigate.

A resource has a URL, but that might not be the only information necessary to identify it. For example, a form submission that uses HTTP POST would also have the HTTP method and payload. Similarly, an iframe srcdoc document needs to know the data it is to use.

Navigation always involves source browsing context, which is the browsing context which was responsible for starting the navigation.

To navigate a browsing context browsingContext to a resource resource, optionally with an exceptions enabled flag, the user agent must run these steps:

  1. If resource is a URL, then set resource to a new request whose url is resource.

  2. If there is a preexisting attempt to navigate browsingContext, and the source browsing context is the same as browsingContext, and that attempt is currently running the unload a document algorithm, then abort these steps without affecting the preexisting attempt to navigate browsingContext.

  3. If the prompt to unload a document algorithm is being run for the active document of browsingContext, then abort these steps without affecting the prompt to unload a document algorithm.

  4. Cancel any preexisting but not yet mature attempt to navigate browsingContext, including canceling any instances of the fetch algorithm started by those attempts. If one of those attempts has already created and initialized a new Document object, abort that Document also. (Navigation attempts that have matured already have session history entries, and are therefore handled during the update the session history with the new page algorithm, later.)

  5. Prompt to unload the active document of browsingContext. ユーザーが文書をアンロードできるようにすることを拒否した場合、これらの手順を中止する。

    If this instance of the navigation algorithm gets canceled while this step is running, the prompt to unload a document algorithm must nonetheless be run to completion.

  6. Abort the active document of browsingContext.

  7. If browsingContext is a nested browsing context, then put it in the delaying load events mode.

    The user agent must take this nested browsing context out of the delaying load events mode when this navigation algorithm later matures, or when it terminates (whether due to having run all the steps, or being canceled, or being aborted), whichever happens first.

  8. Let navigationType be "form-submission" if the navigation algorithm was invoked as a result of the form submission algorithm, and "other" otherwise.

  9. Return to whatever algorithm invoked the navigation steps and continue running these steps in parallel.

  10. This is the step that attempts to obtain resource, if necessary. Jump to the first appropriate substep:

    If resource is a response

    Run process a navigate response with null, resource, navigationType, the source browsing context, and browsingContext, and then abort these steps.

    If resource is a request whose url's scheme is "javascript"

    Queue a task to run these "javascript: URL" steps, associated with the active document of browsingContext:

    1. Let result be undefined, and jump to the step labeled process result below if either of the following are true:

    2. Let urlString be the result of running the URL serializer on resource's url.

    3. Remove the leading "javascript:" string from urlString.

    4. Let script source be the result of applying the percent decode algorithm to urlString.

    5. Replace script source with the result of applying the UTF-8 decode algorithm to script source.

    6. Let address be the URL of the active document of browsingContext.

    7. Let settings be the relevant settings object for the active document of browsingContext.

    8. Let script be the result of creating a classic script given script source and settings.

    9. Let result be the result of running the classic script script. If evaluation was unsuccessful, let result be undefined instead. (The result will also be undefined if scripting is disabled.)

    10. Let response be null.

    11. Process result: If Type(result) is not String, then set response to a response whose status is 204.

      Otherwise, set response a response whose header list consists of `Content-Type`/`text/html` and `Referrer-Policy`/settings's referrer policy, whose body is result, and whose HTTPS state is settings's HTTPS state.

      The exact conversion between the JavaScript string result and the bytes that comprise a response body is not yet specified, pending further investigation into user agent behavior. See issue #1129.

      When it comes time to set the document's address, use address as the override URL.

    12. Run process a navigate response with resource, response, navigationType, the source browsing context, and browsingContext, and then abort these steps.

    The task source for this task is the DOM manipulation task source.

    So for example a javascript: URL in an href attribute of an a element would only be evaluated when the link was followed, while such a URL in the src attribute of an iframe element would be evaluated in the context of the iframe's own nested browsing context when the iframe is being set up; once evaluated, its return value (if it was a string) would replace that browsing context's Document, thus also changing the Window object of that browsing context.

    If resource is to be fetched using `GET`, and there are relevant application caches that are identified by a URL with the same origin as the URL in question, and that have this URL as one of their entries, excluding entries marked as foreign, and whose mode is fast, and the user agent is not in a mode where it will avoid using application caches

    Fetch resource from the most appropriate application cache of those that match.

    For example, imagine an HTML page with an associated application cache displaying an image and a form, where the image is also used by several other application caches. If the user right-clicks on the image and chooses "View Image", then the user agent could decide to show the image from any of those caches, but it is likely that the most useful cache for the user would be the one that was used for the aforementioned HTML page. On the other hand, if the user submits the form, and the form does a POST submission, then the user agent will not use an application cache at all; the submission will be made to the network.

    This still needs to be integrated with the Fetch standard. [FETCH]

    If resource is a request whose url's scheme is a fetch scheme

    Run process a navigate fetch given resource, the source browsing context, and browsing context, and type.

    Otherwise, resource is a request whose url's scheme is neither "javascript" nor a fetch scheme

    Run process a navigate URL scheme given resource's url and browsingContext.

To process a navigate fetch, given a request request, browsing context sourceBrowsingContext, browsing context browsingContext, and string type, run these steps:

  1. Let response be null.

  2. Set request's client to sourceBrowsingContext's active document's relevant settings object, destination to "document", mode to "navigate", credentials mode to "include", use-URL-credentials flag, redirect mode to "manual", and target client id to browsingContext's active document's relevant settings object's id.

  3. If browsingContext is a child browsing context and the browsing context container of browsingContext has a browsing context scope origin, then set request's origin to that browsing context scope origin.

  4. Create a new environment reservedEnvironment, and set its id to a new unique opaque string, its creation URL to request's url, and its target browsing context to browsingContext.

    The created environment's active service worker is set in the handle fetch algorithm during the fetch if its creation URL matches a service worker registration. [SW]

  5. Set request's reserved client to reservedEnvironment.

  6. If the Should navigation request of type from source in target be blocked by Content Security Policy? algorithm returns "Blocked" when executed upon request, navigationType, sourceBrowsingContext, and browsingContext, then set response to a network error. [CSP]

    Otherwise:

    1. Fetch request.

    2. Wait for the task on the networking task source to process response and set response to the result.

  7. Otherwise, if response has a location URL that is a URL whose scheme is "blob", "file", "filesystem", or "javascript", then set response to a network error.

  8. Otherwise, if response has a location URL that is a URL whose scheme is a fetch scheme, then run process a navigate fetch with a new request whose url is response's location URL, sourceBrowsingContext, browsingContext, and type.

  9. Otherwise, if response has a location URL that is a URL, run the process a navigate URL scheme given response's location URL and browsingContext.

  10. Fallback in prefer-online mode: If response was not fetched from an application cache, and was to be fetched using `GET`, and there are relevant application caches that are identified by a URL with the same origin as the URL in question, and that have this URL as one of their entries, excluding entries marked as foreign, and whose mode is prefer-online, and the user didn't cancel the navigation attempt during the earlier step, and response is either a network error or its status is not an ok status, then:

    Let candidate be the response identified by the URL in question from the most appropriate application cache of those that match.

    If candidate is not marked as foreign, then the user agent must discard the failed load and instead continue along these steps using candidate as response. The user agent may indicate to the user that the original page load failed, and that the page used was a previously cached response.

  11. Fallback for fallback entries: If response was not fetched from an application cache, and was to be fetched using `GET`, and its URL matches the fallback namespace of one or more relevant application caches, and the most appropriate application cache of those that match does not have an entry in its online safelist that has the same origin as response's URL and that is a prefix match for response's URL, and the user didn't cancel the navigation attempt during the earlier step, and response is either a network error or its status is not an ok status, then:

    Let candidate be the fallback response specified for the fallback namespace in question. If multiple application caches match, the user agent must use the fallback of the most appropriate application cache of those that match.

    If candidate is not marked as foreign, then the user agent must discard the failed load and instead continue along these steps using candidate as response. The document's URL, if appropriate, will still be the originally requested URL, not the fallback URL, but the user agent may indicate to the user that the original page load failed, that the page used was a fallback response, and what the URL of the fallback response actually is.

  12. Run process a navigate response given request, response, navigationType, the source browsing context, browsingContext, and reservedEnvironment.

To process a navigate response, given a request request, a response response, a string type, two browsing contexts source and browsingContext, and an optional environment reservedEnvironment, run these steps:

  1. If any of the following are true, then display the inline content with an appropriate error shown to the user, with the newly created Document object's origin set to a new opaque origin, and abort these steps.

    This is where the network errors defined and propagated by the WHATWG Fetch standard, such as DNS or TLS errors, end up being displayed to users. [FETCH]

  2. If response's status is 204 or 205, then abort these steps.

  3. If response has an `Content-Disposition` header specifying the attachment disposition type, then handle it as a download and abort these steps.

  4. Let type be the computed type of response.

  5. If the user agent has been configured to process resources of the given type using some mechanism other than rendering the content in a browsing context, then skip this step. Otherwise, if the type is one of the following types, jump to the appropriate entry in the following list, and process response as described there:

    an HTML MIME type
    Follow the steps given in the HTML document section, and then, once they have completed, abort this navigate algorithm.
    an XML MIME type that is not an explicitly supported XML type
    Follow the steps given in the XML document section. If that section determines that the content is not to be displayed as a generic XML document, then proceed to the next step in this overall set of steps. Otherwise, once the steps given in the XML document section have completed, abort this navigate algorithm.
    a JavaScript MIME type
    a JSON MIME type that is not an explicitly supported JSON type
    "text/cache-manifest"
    "text/css"
    "text/plain"
    "text/vtt"
    Follow the steps given in the plain text file section, and then, once they have completed, abort this navigate algorithm.
    "multipart/x-mixed-replace"
    Follow the steps given in the multipart/x-mixed-replace section, and then, once they have completed, abort this navigate algorithm.
    A supported image, video, or audio type
    Follow the steps given in the media section, and then, once they have completed, abort this navigate algorithm.
    A type that will use an external application to render the content in browsingContext
    Follow the steps given in the plugin section, and then, once they have completed, abort this navigate algorithm.

    An explicitly supported XML type is one for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in browsingContext, or a separate application), or one for which the user agent has dedicated processing rules (e.g. a Web browser with a built-in Atom feed viewer would be said to explicitly support the application/atom+xml MIME type), or one for which the user agent has a dedicated handler (e.g. one registered using registerContentHandler()).

    The term JSON MIME type is used to refer to the MIME types application/json, text/json, and any MIME type whose subtype ends with the five characters "+json".

    An explicitly supported JSON type is one for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in browsingContext, or a separate application), or one for which the user agent has dedicated processing rules, or one for which the user agent has a dedicated handler (e.g. one registered using registerContentHandler()).

    Setting the document's address: If there is no override URL, then any Document created by these steps must have its URL set to the URL that was originally to be fetched, ignoring any other data that was used to obtain the resource. However, if there is an override URL, then any Document created by these steps must have its URL set to that URL instead.

    An override URL is set when dereferencing a javascript: URL and when performing an overridden reload.

    Initializing a new Document object: when a Document is created as part of the above steps, the user agent will be required to additionally run the following algorithm after creating the new object:

    1. Let window be null.

    2. Let settingsObject be null.

    3. If browsingContext's only entry in its session history is the about:blank Document that was added when browsingContext was created, and navigation is occurring with replacement enabled, and that Document has the same origin as the new Document, then set window to the Window object of that Document, and set settingsObject to window's relevant settings object.

    4. Otherwise,

      1. Call the JavaScript InitializeHostDefinedRealm() abstract operation with the following customizations:

      2. Set up a browsing context environment settings object with realm execution context and reservedEnvironment, if present, and set settingsObject to the result.

    5. Set window's associated Document to the new Document.

    6. Set browsingContext's WindowProxy object's [[Window]] internal slot value to window.

    7. Set the Document's HTTPS state to the HTTPS state of the response used to generate the document.

    8. Set the Document's referrer policy to the result of parsing the `Referrer-Policy` header of the response used to generate the document. [REFERRERPOLICY]

    9. Execute the Initialize a Document's CSP list algorithm on the Document object and the response used to generate the document. [CSP]

    10. If resource is a request, then set the document's referrer to the serialization of resource's referrer, if resource's referrer is a URL record, and the empty string otherwise.

      Per the WHATWG Fetch standard a request's referrer will be either a URL record or "no-referrer" at this point.

    11. Implement the sandboxing for the Document.

    12. Set the allow* flags for the Document.

    13. Set settingsObject's execution ready flag.

    14. If settingsObject's active service worker is not null, then:

      1. If settingsObject is a secure context, then:

        1. If browsingContext has an opener browsing context and request's client is a non-secure context, then disown browsingContext's opener.

      2. Otherwise, set settingsObject's active service worker to null.

  6. Otherwise, the document's type is such that the resource will not affect browsingContext, e.g., because the resource is to be handed to an external application or because it is an unknown type that will be processed as a download. Process the resource appropriately.

To process a navigate URL scheme, given a URL url and browsing context browsingContext, run these steps:

  1. If url is to be handled using a mechanism that does not affect browsingContext, e.g., because url's scheme is handled externally, then proceed with that mechanism instead.

  2. Otherwise, url is to be handled by displaying some sort of inline content, e.g., an error message because the specified scheme is not one of the supported protocols, or an inline prompt to allow the user to select a registered handler for the given scheme. Display the inline content.

    In the case of a registered handler being used, navigate will be invoked with a new URL.

When a resource is handled by passing its URL or data to an external software package separate from the user agent (e.g. handing a mailto: URL to a mail client, or a Word document to a word processor), user agents should attempt to mitigate the risk that this is an attempt to exploit the target software, e.g. by prompting the user to confirm that the source browsing context's active document's origin is to be allowed to invoke the specified software. In particular, if the navigate algorithm, when it was invoked, was not triggered by user activation, the user agent should not invoke the external software package without prior user confirmation.

For example, there could be a vulnerability in the target software's URL handler which a hostile page would attempt to exploit by tricking a user into clicking a link.


Some of the sections below, to which the above algorithm defers in certain cases, require the user agent to update the session history with the new page. When a user agent is required to do this, it must queue a task (associated with the Document object of the current entry, not the new one) to run the following steps:

  1. Unload the Document object of the current entry, with the recycle parameter set to false.

    If this instance of the navigation algorithm is canceled while this step is running the unload a document algorithm, then the unload a document algorithm must be allowed to run to completion, but this instance of the navigation algorithm must not run beyond this step. (In particular, for instance, the cancelation of this algorithm does not abort any event dispatch or script execution occurring as part of unloading the document or its descendants.)

  2. If the navigation was initiated for entry update of an entry
    1. Replace the Document of the entry being updated, and any other entries that referenced the same document as that entry, with the new Document.

    2. Traverse the history to the new entry.

    If the navigation was initiated with a URL that equals the browsing context's active document's URL
    1. Replace the current entry with a new entry representing the new resource and its Document object, related state, and the default scroll restoration mode of "auto".

    2. Traverse the history to the new entry.

    そうでなければ
    1. Remove all the entries in the browsing context'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. Append a new entry at the end of the History object representing the new resource and its Document object, related state, and the default scroll restoration mode of "auto".

    3. Traverse the history to the new entry. If the navigation was initiated with replacement enabled, then the traversal must itself be initiated with replacement enabled.

  3. The navigation algorithm has now matured.

  4. Fragment loop: Spin the event loop for a user-agent-defined amount of time, as desired by the user agent implementor. (This is intended to allow the user agent to optimize the user experience in the face of performance concerns.)

  5. If the Document object has no parser, or its parser has stopped parsing, or the user agent has reason to believe the user is no longer interested in scrolling to the fragment, then abort these steps.

  6. Scroll to the fragment given in the document's URL. If this fails to find an indicated part of the document, then return to the fragment loop step.

The task source for this task is the networking task source.

7.8.2 Page load processing model for HTML files

When an HTML document is to be loaded in a browsing context, the user agent must queue a task to create a Document object, mark it as being an HTML document, set its content type to "text/html", initialize the Document object, and finally create an HTML parser and associate it with the Document. Each task that the networking task source places on the task queue while fetching runs must then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream.

The input byte stream converts bytes into characters for use in the tokenizer. This process relies, in part, on character encoding information found in the real Content-Type metadata of the resource; the computed type is not used for this purpose.

When no more bytes are available, the user agent must queue a task for the parser to process the implied EOF character, which eventually causes a load event to be fired.

After creating the Document object, but before any script execution, certainly before the parser stops, the user agent must update the session history with the new page.

Application cache selection happens in the HTML parser.

The task source for the two tasks mentioned in this section must be the networking task source.

7.8.3 Page load processing model for XML files

Spec bugs: 17976

When faced with displaying an XML file inline, user agents must follow the requirements defined in the XML and Namespaces in XML recommendations, RFC 7303, DOM, and other relevant specifications to create a Document object and a corresponding XML parser. [XML] [XMLNS] [RFC7303] [DOM]

At the time of writing, the XML specification community had not actually yet specified how XML and the DOM interact.

After the Document is created, the user agent must initialize the Document object.

The actual HTTP headers and other metadata, not the headers as mutated or implied by the algorithms given in this specification, are the ones that must be used when determining the character encoding according to the rules given in the above specifications. Once the character encoding is established, the document's character encoding must be set to that character encoding.

If the document element, as parsed according to the XML specifications cited above, is found to be an html element with an attribute manifest whose value is not the empty string, then, as soon as the element is inserted into the document, the user agent must parse the value of that attribute relative to that element's node document, and if that is successful, must apply the URL serializer algorithm to the resulting URL record with the exclude fragment flag set to obtain manifest URL, and then run the application cache selection algorithm with manifest URL as the manifest URL, passing in the newly-created Document. Otherwise, if the attribute is absent, its value is the empty string, or parsing its value fails, then as soon as the document element is inserted into the document, the user agent must run the application cache selection algorithm with no manifest, and passing in the Document.

Because the processing of the manifest attribute happens only once the document element is parsed, any URLs referenced by processing instructions before the document element (such as PIs) will be fetched from the network and cannot be cached.

User agents may examine the namespace of the root Element node of this Document object to perform namespace-based dispatch to alternative processing tools, e.g. determining that the content is actually a syndication feed and passing it to a feed handler. If such processing is to take place, abort the steps in this section, and jump to the next step (labeled non-document content) in the navigate steps above.

Otherwise, then, with the newly created Document, the user agent must update the session history with the new page. User agents may do this before the complete document has been parsed (thus achieving incremental rendering), and must do this before any scripts are to be executed.

Error messages from the parse process (e.g. XML namespace well-formedness errors) may be reported inline by mutating the Document.

7.8.4 Page load processing model for text files

When a plain text document is to be loaded in a browsing context, the user agent must queue a task to create a Document object, mark it as being an HTML document, set its content type to the computed MIME type of the resource (type in the navigate algorithm), initialize the Document object, create an HTML parser, associate it with the Document, act as if the tokenizer had emitted a start tag token with the tag name "pre" followed by a single U+000A LINE FEED (LF) character, and switch the HTML parser's tokenizer to the PLAINTEXT state. Each task that the networking task source places on the task queue while fetching runs must then fill the parser's input byte stream with the fetched bytes and cause the HTML parser to perform the appropriate processing of the input stream.

The rules for how to convert the bytes of the plain text document into actual characters, and the rules for actually rendering the text to the user, are defined by the specifications for the computed MIME type of the resource (type in the navigate algorithm).

The document's character encoding must be set to the character encoding used to decode the document.

Upon creation of the Document object, the user agent must run the application cache selection algorithm with no manifest, and passing in the newly-created Document.

When no more bytes are available, the user agent must queue a task for the parser to process the implied EOF character, which eventually causes a load event to be fired.

After creating the Document object, but potentially before the page has finished parsing, the user agent must update the session history with the new page.

User agents may add content to the head element of the Document, e.g., linking to a style sheet, providing script, or giving the document a title.

In particular, if the user agent supports the Format=Flowed feature of RFC 3676 then the user agent would need to apply extra styling to cause the text to wrap correctly and to handle the quoting feature. This could be performed using, e.g., a CSS extension.

The task source for the two tasks mentioned in this section must be the networking task source.

7.8.5 Page load processing model for multipart/x-mixed-replace resources

When a resource with the type multipart/x-mixed-replace is to be loaded in a browsing context, the user agent must parse the resource using the rules for multipart types. [RFC2046]

For each body part obtained from the resource, the user agent must run process a navigate response using the new body part and the same browsing context, with replacement enabled if a previous body part from the same resource resulted in a Document object being created and initialized, and otherwise using the same setup as the navigate attempt that caused this section to be invoked in the first place.

For the purposes of algorithms processing these body parts as if they were complete stand-alone resources, the user agent must act as if there were no more bytes for those resources whenever the boundary following the body part is reached.

Thus, load events (and for that matter unload events) do fire for each body part loaded.

7.8.6 Page load processing model for media

When an image, video, or audio resource is to be loaded in a browsing context, the user agent should create a Document object, mark it as being an HTML document, set its content type to the computed MIME type of the resource (type in the navigate algorithm), initialize the Document object, append an html element to the Document, append a head element and a body element to the html element, append an element host element for the media, as described below, to the body element, and set the appropriate attribute of the element host element, as described below, to the address of the image, video, or audio resource.

The element host element to create for the media is the element given in the table below in the second cell of the row whose first cell describes the media. The appropriate attribute to set is the one given by the third cell in that same row.

Type of media Element for the media Appropriate attribute
画像 img src
Video video src
Audio audio src

Then, the user agent must act as if it had stopped parsing.

Upon creation of the Document object, the user agent must run the application cache selection algorithm with no manifest, and passing in the newly-created Document.

After creating the Document object, but potentially before the page has finished fully loading, the user agent must update the session history with the new page.

User agents may add content to the head element of the Document, or attributes to the element host element, e.g., to link to a style sheet, to provide a script, to give the document a title, or to make the media autoplay.

7.8.7 Page load processing model for content that uses plugins

When a resource that requires an external resource to be rendered is to be loaded in a browsing context, the user agent should create a Document object, mark it as being an HTML document and mark it as being a plugin document, set its content type to the computed MIME type of the resource (type in the navigate algorithm), initialize the Document object, append an html element to the Document, append a head element and a body element to the html element, append an embed to the body element, and set the src attribute of the embed element to the address of the resource.

The term plugin document is used by Content Security Policy as part of the mechanism that ensures iframes can't be used to evade plugin-types directives. [CSP]

Then, the user agent must act as if it had stopped parsing.

Upon creation of the Document object, the user agent must run the application cache selection algorithm with no manifest, and passing in the newly-created Document.

After creating the Document object, but potentially before the page has finished fully loading, the user agent must update the session history with the new page.

User agents may add content to the head element of the Document, or attributes to the embed element, e.g. to link to a style sheet or to give the document a title.

If the Document's active sandboxing flag set has its sandboxed plugins browsing context flag set, the synthesized embed element will fail to render the content if the relevant plugin cannot be secured.

7.8.8 Page load processing model for inline content that doesn't have a DOM

When the user agent is to display a user agent page inline in a browsing context, the user agent should create a Document object, mark it as being an HTML document, set its content type to "text/html", initialize the Document object, and then either associate that Document with a custom rendering that is not rendered using the normal Document rendering rules, or mutate that Document until it represents the content the user agent wants to render.

Once the page has been set up, the user agent must act as if it had stopped parsing.

Upon creation of the Document object, the user agent must run the application cache selection algorithm with no manifest, passing in the newly-created Document.

After creating the Document object, but potentially before the page has been completely set up, the user agent must update the session history with the new page.

7.8.9 Navigating to a fragment

When a user agent is supposed to navigate to a fragment, then the user agent must run the following steps:

  1. Remove all the entries in the browsing context'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. Append a new entry at the end of the History object representing the new resource and its Document object, related state, and current entry's scroll restoration mode. Its URL must be set to the address to which the user agent was navigating. The title must be left unset.

  4. Traverse the history to the new entry, with the non-blocking events flag set. This will scroll to the fragment given in what is now the document's URL.

If the scrolling fails because the relevant ID has not yet been parsed, then the original navigation algorithm will take care of the scrolling instead, as the last few steps of its update the session history with the new page algorithm.


When the user agent is required to scroll to the fragment and the indicated part of the document, if any, is being rendered, the user agent must either change the scrolling position of the document using the following algorithm, or perform some other action such that the indicated part of the document is brought to the user's attention. If there is no indicated part, or if the indicated part is not being rendered, then the user agent must do nothing. The aforementioned algorithm is as follows:

  1. If there is no indicated part of the document, set the Document's target element to null.

  2. If the indicated part of the document is the top of the document, then:

    1. Set the Document's target element to null.

    2. Scroll to the beginning of the document for the Document. [CSSOMVIEW]

  3. Otherwise:

    1. Let target be element that is the indicated part of the document.

    2. Set the Document's target element to target.

    3. Use the scroll an element into view algorithm to scroll target into view, with the align to top flag set. [CSSOMVIEW]

    4. Run the focusing steps for target, with the Document's viewport as the fallback target.

    5. Move the sequential focus navigation starting point to target.

The indicated part of the document is the one that the fragment, if any, identifies. The semantics of the fragment in terms of mapping it to a node is defined by the specification that defines the MIME type used by the Document (for example, the processing of fragments for XML MIME types is the responsibility of RFC7303). [RFC7303]

There is also a target element for each Document, which is used in defining the :target pseudo-class and is updated by the above algorithm. It is initially null.

For HTML documents (and HTML MIME types), the following processing model must be followed to determine what the indicated part of the document is.

  1. Apply the URL parser algorithm to the URL, and let fragid be the fragment component of the resulting URL record.

  2. If fragid is the empty string, then the indicated part of the document is the top of the document; stop the algorithm here.

  3. Let fragid bytes be the result of percent-decoding fragid.

  4. Let decoded fragid be the result of running UTF-8 decode without BOM or fail on fragid bytes. If decoded fragid is failure, jump to the step labeled no decoded fragid.

  5. If there is an element in the document tree that has an ID exactly equal to decoded fragid, then the first such element in tree order is the indicated part of the document; stop the algorithm here.

  6. No decoded fragid: If there is an a element in the document tree that has a name attribute whose value is exactly equal to fragid (not decoded fragid), then the first such element in tree order is the indicated part of the document; stop the algorithm here.

  7. If fragid is an ASCII case-insensitive match for the string top, then the indicated part of the document is the top of the document; stop the algorithm here.

  8. Otherwise, there is no indicated part of the document.

The task source for the task mentioned in this section must be the DOM manipulation task source.

7.8.10 履歴走査

When a user agent is required to traverse the history to a session history entry entry, optionally with replacement enabled, and optionally with the non-blocking events flag set, the user agent must act as follows.

This algorithm is not just invoked when explicitly going back or forwards in the session history — it is also invoked in other situations, for example when navigating a browsing context, as part of updating the session history with the new page.

  1. If entry no longer holds a Document object, then navigate the browsing context to entry's URL to perform an entry update of entry, and abort these steps. The "navigate" algorithm reinvokes this "traverse" algorithm to complete the traversal, at which point there is a Document object and so this step gets skipped. The navigation must be done using the same source browsing context as was used the first time entry was created. (This can never happen with replacement enabled.)

    If the resource was obtained using a non-idempotent action, for example a POST form submission, or if the resource is no longer available, for example because the computer is now offline and the page wasn't cached, navigating to it again might not be possible. In this case, the navigation will result in a different page than previously; for example, it might be an error message explaining the problem or offering to resubmit the form.

  2. If the current entry's title was not set by the pushState() or replaceState() methods, then set its title to the value returned by the document.title IDL attribute.

  3. If appropriate, update the current entry in the browsing context's Document object's History object to reflect any state that the user agent wishes to persist. The entry is then said to be an entry with persisted user state.

  4. If entry has a different Document object than the current entry, then run the following substeps:

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

    2. If the origin of entry's Document object is not the same as the origin of the current entry's Document object, then run the following subsubsteps:

      1. The current browsing context name must be stored with all the entries in the history that are associated with Document objects with the same origin as the active document and that are contiguous with the current entry.

      2. If the browsing context is a top-level browsing context, but not an auxiliary browsing context, then set the browsing context's name to the empty string.

    3. Make entry's Document object the active document of the browsing context.

    4. If entry has a browsing context name, then run the following subsubsteps:

      1. Set the browsing context's browsing context name to entry's browsing context name.

      2. Clear any browsing context names of all entries in the history that are associated with Document objects with the same origin as the new active document and that are contiguous with entry.

    5. If entry's Document object has any form controls whose autofill field name is "off", invoke the reset algorithm of each of those elements.

    6. If the current document readiness of entry's Document object is "complete", then queue a task to run the following subsubsteps:

      1. If the Document's page showing flag is true, then abort this task (i.e. don't fire the event below).

      2. Set the Document's page showing flag to true.

      3. Run any session history document visibility change steps for Document that are defined by other applicable specifications.

        This is specifically intended for use by the Page Visibility specification. [PAGEVIS]

      4. Fire an event named pageshow at the Document object's Window object, using PageTransitionEvent, with the persisted attribute initialized to true, and legacy target override flag set.

  5. Set the document's URL to entry's URL.

  6. If entry has a URL whose fragment differs from that of the current entry's when compared in a case-sensitive manner, and the two share the same Document object, then let hash changed be true, and let old URL be the current entry's URL and new URL be entry's URL. Otherwise, let hash changed be false.

  7. If the traversal was initiated with replacement enabled, remove the entry immediately before the specified entry in the session history.

  8. If entry is not an entry with persisted user state, but its URL's fragment is non-null, then scroll to the fragment.

  9. Set the current entry to entry.

  10. Let targetRealm be the current Realm Record.

  11. If entry has a state object, then let state be StructuredClone(entry's state object, targetRealm). Otherwise, let state be null.

  12. Set history.state to state.

  13. Let state changed be true if entry's Document object has a latest entry, and that entry is not entry; otherwise let it be false.

  14. Set entry's Document object's latest entry to entry.

  15. If the non-blocking events flag is not set, then run the following substeps immediately. Otherwise, the non-blocking events flag is set; queue a task to run the following substeps instead.

    1. If state changed is true, then fire an event named popstate at the Document object's Window object, using PopStateEvent, with the bubbles attribute initialized to true and the state attribute initialized state.

    2. If entry is an entry with persisted user state, then the user agent may restore persisted user state and update aspects of the document and its rendering.

    3. If hash changed is true, then fire an event named hashchange at the browsing context's Window object, using HashChangeEvent, with the bubbles attribute initialized to true, the oldURL attribute initialized to old URL, and the newURL attribute initialized to new URL.

The task source for the tasks mentioned above is the DOM manipulation task source.

7.8.10.1 Persisted user state restoration

When the user agent is to restore persisted user state from a history entry, it must run the following steps immediately:

  1. If the entry has a scroll restoration mode, let scrollRestoration be that. Otherwise let scrollRestoration be "auto"

  2. If scrollRestoration is "manual" the user agent should not restore the scroll position for the Document or any of its scrollable regions, with the exception of any nested browsing contexts whose scroll restoration is controlled by their own history entry's scroll restoration mode, otherwise, it may do so.

  3. Optionally, update other aspects of the document and its rendering, for instance values of form fields, that the user agent had previously recorded.

This can even include updating the dir attribute of textarea elements or input elements whose type attribute is in either the Text state or the Search state, if the persisted state includes the directionality of user input in such controls.

Not restoring the scroll position by user agent does not imply that the scroll position will be left at any particular value (e.g., (0,0)). The actual scroll position depends on the navigation type and the user agent's particular caching strategy. So web applications cannot assume any particular scroll position but rather are urged to set it to what they want it to be.

7.8.10.2 The PopStateEvent interface
[Constructor(DOMString type, optional PopStateEventInit eventInitDict)]
interface PopStateEvent : Event {
  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.8.10.3 The HashChangeEvent interface

Support: hashchangeChrome for Android 56+Chrome 5+iOS Safari 4.0+UC Browser for Android 11+Firefox 3.6+IE 8+Samsung Internet 4+Opera Mini NoneAndroid Browser 2.2+Safari 5+Edge 12+Opera 10.6+

Source: caniuse.com

[Constructor(DOMString type, optional HashChangeEventInit eventInitDict)]
interface HashChangeEvent : Event {
  readonly attribute USVString oldURL;
  readonly attribute USVString newURL;
};

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

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

event . newURL

今現在であるセッション履歴のエントリ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.8.10.4 The PageTransitionEvent interface
[Constructor(DOMString type, optional PageTransitionEventInit eventInitDict)]
interface PageTransitionEvent : Event {
  readonly attribute boolean persisted;
};

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

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

pagehideイベントに対して、ページが最後の時間まで出かける場合はfalseを返す。そうでなければ、(何もページを最上にしないよう共謀しない場合)、ユーザーがこのページに戻る場合、ページが再利用されるかもしれないことを意味し、trueを返す。

最上でないページを含む可能性があるもの:

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

7.8.11 文書の解放

A Document has a salvageable state, which must initially be true, a fired unload flag, which must initially be false, and a page showing flag, which must initially be false. The page showing flag is used to ensure that scripts receive pageshow and pagehide events in a consistent manner (e.g. that they never receive two pagehide events in a row without an intervening pageshow, or vice versa).

Event loops have a termination nesting level counter, which must initially be zero.

When a user agent is to prompt to unload a document, it must run the following steps.

  1. Increase the event loop's termination nesting level by one.

  2. Increase the Document's ignore-opens-during-unload counter by one.

  3. Let event be the result of creating an event using BeforeUnloadEvent.

  4. Initialize event's type attribute to beforeunload and its cancelable attribute true.

  5. Dispatch: Dispatch event at the Document's Window object.

  6. Decrease the event loop's termination nesting level by one.

  7. If any event listeners were triggered by the earlier dispatch step, then set the Document's salvageable state to false.

  8. If the Document's active sandboxing flag set does not have its sandboxed modals flag set, and the returnValue attribute of the event object is not the empty string, or if the event was canceled, then the user agent may ask the user to confirm that they wish to unload the document.

    The message shown to the user is not customizable, but instead determined by the user agent. In particular, the actual value of the returnValue attribute is ignored.

    The user agent is encouraged to avoid asking the user for confirmation if it judges that doing so would be annoying, deceptive, or pointless. A simple heuristic might be that if the user has not interacted with the document, the user agent would not ask for confirmation before unloading it.

    If the user agent asks the user for confirmation, it must pause while waiting for the user's response.

    If the user did not confirm the page navigation, then the user agent refused to allow the document to be unloaded.

  9. If this algorithm was invoked by another instance of the "prompt to unload a document" algorithm (i.e. through the steps below that invoke this algorithm for all descendant browsing contexts), then jump to the step labeled end.

  10. Let descendants be the list of the descendant browsing contexts of the Document.

  11. If descendants is not an empty list, then for each browsing context b in descendants run the following substeps:

    1. Prompt to unload the active document of the browsing context b. If the user refused to allow the document to be unloaded, then the user implicitly also refused to allow this document to be unloaded; jump to the step labeled end.

    2. If the salvageable state of the active document of the browsing context b is false, then set the salvageable state of this document to false also.

  12. End: Decrease the Document's ignore-opens-during-unload counter by one.

When a user agent is to unload a document, it must run the following steps. These steps are passed an argument, recycle, which is either true or false, indicating whether the Document object is going to be re-used. (This is set by the document.open() method.)

  1. Increase the event loop's termination nesting level by one.

  2. Increase the Document's ignore-opens-during-unload counter by one.

  3. If the Document's page showing flag is false, then jump to the step labeled unload event below (i.e. skip firing the pagehide event and don't rerun the unloading document visibility change steps).

  4. Set the Document's page showing flag to false.

  5. Fire an event named pagehide at the Document object's Window object, using PageTransitionEvent, with the persisted attribute initialized to true if the Document object's salvageable state is true, and false otherwise, and legacy target override flag set.

  6. Run any unloading document visibility change steps for Document that are defined by other applicable specifications.

    This is specifically intended for use by the Page Visibility specification. [PAGEVIS]

  7. Unload event: If the Document's fired unload flag is false, then fire an event named unload at the Document's object Window object, with legacy target override flag set.

  8. Decrease the event loop's termination nesting level by one.

  9. If any event listeners were triggered by the earlier unload event step, then set the Document object's salvageable state to false and set the Document's fired unload flag to true.

  10. Run any unloading document cleanup steps for Document that are defined by this specification and other applicable specifications.

  11. If this algorithm was invoked by another instance of the "unload a document" algorithm (i.e. by the steps below that invoke this algorithm for all descendant browsing contexts), then jump to the step labeled end.

  12. Let descendants be the list of the descendant browsing contexts of the Document.

  13. If descendants is not an empty list, then for each browsing context b in descendants run the following substeps:

    1. Unload the active document of the browsing context b with the recycle parameter set to false.

    2. If the salvageable state of the active document of the browsing context b is false, then set the salvageable state of this document to false also.

  14. If both the Document's salvageable state and recycle are false, then the Document's browsing context must discard the Document.

  15. End: Decrease the Document's ignore-opens-during-unload counter by one.

This specification defines the following unloading document cleanup steps. Other specifications can define more.

  1. Let window be the Document's Window object.

  2. For each WebSocket object webSocket whose relevant global object is equal to window, make disappear webSocket.

    If this affected any WebSocket objects, then set the Document's salvageable state to false.

  3. If the Document's salvageable state is false, run the following substeps:

    1. For each EventSource object eventSource whose relevant global object is equal to window, forcibly close eventSource.

    2. Empty window's list of active timers.

7.8.11.1 The BeforeUnloadEvent interface
interface BeforeUnloadEvent : Event {
  attribute DOMString returnValue;
};

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

The BeforeUnloadEvent interface is a legacy interface which allows prompting to unload the document to be controlled not only by canceling the event, but by setting the returnValue attribute to a value besides the empty string. Authors should use the preventDefault() method, or other means of canceling events, instead of using returnValue.

The returnValue attribute controls the process of prompting to unload the document. 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.

7.8.12 Aborting a document load

If a Document is aborted, the user agent must run the following steps:

  1. Abort the active documents of every child browsing context. If this results in any of those Document objects having their salvageable state set to false, then set this Document's salvageable state to false also.

  2. Cancel any instances of the fetch algorithm in the context of this Document, discarding any tasks queued for them, and discarding any further data received from the network for them. If this resulted in any instances of the fetch algorithm being canceled or any queued tasks or any network data getting discarded, then set the Document's salvageable state to false.

  3. If the Document has an active parser, then abort that parser and set the Document's salvageable state to false.

User agents may allow users to explicitly invoke the abort a document algorithm for a Document. If the user does so, then, if that Document is an active document, the user agent should queue a task to fire an event named abort at that Document's Window object before invoking the abort algorithm.

7.9 オフラインウェブアプリケーション

Support: offline-appsChrome for Android 56+Chrome 4+iOS Safari 3.2+UC Browser for Android 11+Firefox 3.5+IE 10+Samsung Internet 4+Opera Mini NoneAndroid Browser 2.1+Safari 4+Edge 12+Opera 10.6+

Source: caniuse.com

This feature is in the process of being removed from the Web platform. (This is a long process that takes many years.) Using any of the offline Web application features at this time is highly discouraged. Use service workers instead. [SW]

7.9.1 導入

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

ネットワーク接続が利用できない場合―たとえば、ユーザーがISPのカバレッジエリアの外に移動しているため―でも、ユーザーにウェブアプリケーションおよび文書との対話を継続できるようにするために、著者は、オフラインで作業し、オフラインで使用のためにファイルのコピーを保持するためにユーザーのブラウザーになる、ウェブアプリケーション用に必要とされるファイルの一覧を示したマニフェストを提供できる。

これを説明するために、HTMLページ"clock1.html"、CSSスタイルシート"clock.css"、およびJavaScriptスクリプト"clock.js"から成る単純な時計アプレットを考えてみる。

マニフェストを追加する前に、これらの3つのファイルは次のようになる:

<!-- clock1.html -->
<!DOCTYPE HTML>
<html>
 <head>
  <meta charset="utf-8">
  <title>Clock</title>
  <script src="clock.js"></script>
  <link rel="stylesheet" href="clock.css">
 </head>
 <body>
  <p>The time is: <output id="clock"></output></p>
 </body>
</html>
/* clock.css */
output { font: 2em sans-serif; }
/* clock.js */
setInterval(function () {
    document.getElementById('clock').value = new Date();
}, 1000);

ユーザーがオフライン時に"clock1.html"ページを開こうとする場合、しかし、(ローカルキャッシュにまだ持つ場合を除いて)ユーザーエージェントはエラーとともに失敗する。

著者は、代わりに"clock.appcache"という、3つのファイルのマニフェストを提供できる:

CACHE MANIFEST
clock2.html
clock.css
clock.js

HTMLファイルへの小さな変化とともに、(text/cache-manifestで提供される)マニフェストがアプリケーションにリンクされている:

<!-- clock2.html -->
<!DOCTYPE HTML>
<html manifest="clock.appcache">
 <head>
  <meta charset="utf-8">
  <title>Clock</title>
  <script src="clock.js"></script>
  <link rel="stylesheet" href="clock.css">
 </head>
 <body>
  <p>The time is: <output id="clock"></output></p>
 </body>
</html>

さて、ユーザーがページに行く場合、ブラウザーはファイルをキャッシュし、ユーザーがオフラインである場合でも、それらを使用できるようにする。

著者はまた、マニフェストのメインページを含めることを推奨するが、実際にマニフェストを参照されるページは、明示的に言及されない場合でも、自動的にキャッシュされる。

"no-store"ディレクティブ例外とともに、TLSで供給される(https:を使用して暗号化される)キャッシュページでのHTTPキャッシュヘッダーと制限は、マニフェストによって上書きされる。したがって、ページは、ユーザーエージェントがそれを更新する前にアプリケーションキャッシュから期限切れにならず、TLS経由で提供されるアプリケーションはオフラインで動作させることができる。

この例をオンラインで見る

7.9.1.1 レガシーアプリケーションへのオフラインキャッシュのサポート

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

マニフェストに記載されかつアプリケーションキャッシュに格納されたロジック(マークアップ、スクリプト、スタイルシート、画像など)とともに、アプリケーションに対する有限数の静的HTMLページとともに、およびウェブストレージまたはサーバー側にインデックス付けされたデータベースに格納されたアプリケーションおよびユーザーデーターとともに、アプリケーションロジックがアプリケーションとユーザーデータから別れる場合、アプリケーションキャッシュ機能は最も機能的に動作し、ウェブソケット、XMLHttpRequest、サーバーに送信されるイベント、または他の同様の機構を使用して動的に更新される。

このモデルはユーザーに対して高速な経験をもたらす:(おそらく古いデータを示しつつ)アプリケーション即時に読み込み、ネットワークがそれを可能にするように、新鮮なデータを高速に得られる。

しかし、レガシーアプリケーションは、サーバーから新しいHTMLページで得られた各操作とともに、ユーザーデータおよびロジックがHTMLと一緒に混合されるように設計される傾向にある。

たとえば、ニュースアプリケーションを考えてみよう。このようなアプリケーションの典型的なアーキテクチャーは、アプリケーションキャッシュ機能を使用しない場合、ユーザーはメインページをフェッチし、サーバーは現在の見出しとユーザーインタフェースロジックを一緒に混合した動的に生成されるページを返す。

しかし、アプリケーションキャッシュ機能のために設計されたニュースアプリケーションは、ロジックでのみ構成されるメインページを代わりに持つだろうし、メインページがサーバーとは別にデータをフェッチしているだろう。たとえば、XMLHttpRequestを使用して。

混合コンテンツモデルは、アプリケーションのキャッシュ機能とともにうまく動作しない:コンテンツがキャッシュされているので、常にキャッシュが更新された前回から古いデータを見て、ユーザーにもたらすだろう。

分離されたモデルと同じ速さで、従来のモデルを動作させる方法がないが、それは少なくとも好ましいオンラインアプリケーションキャッシュモードを使用してオフライン利用で使用するために改造できる。これを行うには、アプリケーションキャッシュマニフェストでオフライン作業をしたいHTMLページによって使用されるすべての静的リソースを一覧表示し、HTMLファイルからそのマニフェストを選択するmanifest属性を使用し、マニフェストの一番下に次の行を追加する:

SETTINGS:
prefer-online
NETWORK:
*

ユーザーがオフラインである際に、許可するすべてのリソースが通常アクセスされるマニフェストに記載されていない一方で、これは、マスターエントリにのみ使用されるアプリケーションキャッシュを引き起こし、(本質的にマニフェストに記載されているリソースをピン留めする)分割不能なHTTPキャッシュとして使用されるアプリケーションキャッシュを引き起こす。

7.9.1.2 イベントの概要

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

ユーザーがマニフェストを宣言するページを訪問する際に、ブラウザーはキャッシュを更新しようとする。これは、ユーザーエージェントが最後にそれを見てからマニフェストが変更された場合、それが言及されているすべてのリソースを再ダウンロードして改めてキャッシュし、マニフェストのコピーを取得することによってこれを行う。

これが起こっているように、ユーザーに適切な方法で通知できるように、イベントの数は、キャッシュの更新の状態へと更新されたスクリプトを保つためにApplicationCacheオブジェクトで発火する。イベントは次のとおり:

イベント名 インターフェイス 発火条件 次のイベント
checking Event ユーザーエージェントは、更新をチェックする、または初回のマニフェストをダウンロードしようとしている。これは、常にシーケンスの最初のイベントである。 noupdatedownloadingobsoleteerror
noupdate Event マニフェストは変更されなかった。 シーケンス内の最後のイベント。
downloading Event ユーザーエージェントは更新を発見し、それをフェッチしている、または初回のマニフェストで記載されたリソースをダウンロードしている。 progresserrorcachedupdateready
progress ProgressEvent ユーザーエージェントは、マニフェストで記載されたリソースをダウンロードしている。イベントオブジェクトのtotal属性は、ダウンロードされたファイルの合計数を返す。イベントオブジェクトのloaded属性は、これまでに処理されたファイルの数を返す。 progresserrorcachedupdateready
cached Event マニフェストに記載されたリソースがダウンロードされ、アプリケーションがキャッシュされた。 シーケンス内の最後のイベント。
updateready Event マニフェストに記載されたリソースは新しく再ダウンロードされており、スクリプトは新しいキャッシュに切り替えるためにswapCache()を使用できる。 シーケンス内の最後のイベント。
obsolete Event マニフェストは404または410ページになっていることが判明し、アプリケーションのキャッシュを削除している。 シーケンス内の最後のイベント。
error Event マニフェストが404または410ページだったので、アプリケーションをキャッシュする試みが中止された。 シーケンス内の最後のイベント。
マニフェストは変更されなかったが、マニフェストを参照するページが正しくダウンロードでなかった。
マニフェストに記載されたリソースを取得するときに致命的なエラーが発生した。
更新されている間にマニフェストが変更された。 ユーザーエージェントは、再び一時的にファイルを取得しようする。

これらのイベントはキャンセル可能である。それらのデフォルトアクションは、ダウンロードの進捗情報を表示するためのユーザーエージェントに対するものである。ページが独自のアップデートのUIが表示する場合、イベントのキャンセルは、冗長な進捗情報の表示からユーザーエージェントを防ぐだろう。

7.9.2 Application caches

An application cache is a set of cached resources consisting of:

Each application cache has a completeness flag, which is either complete or incomplete.


An application cache group is a group of application caches, identified by the absolute URL of a resource manifest which is used to populate the caches in the group.

An application cache is newer than another if it was created after the other (in other words, application caches in an application cache group have a chronological order).

Only the newest application cache in an application cache group can have its completeness flag set to incomplete; the others are always all complete.

Each application cache group has an update status, which is one of the following: idle, checking, downloading.

A relevant application cache is an application cache that is the newest in its group to be complete.

Each application cache group has a list of pending master entries. Each entry in this list consists of a resource and a corresponding Document object. It is used during the application cache download process to ensure that new master entries are cached even if the application cache download process was already running for their application cache group when they were loaded.

An application cache group can be marked as obsolete, meaning that it must be ignored when looking at what application cache groups exist.


A cache host is a Document object.

Each cache host has an associated ApplicationCache object.

Each cache host initially is not associated with an application cache, but can become associated with one early during the page load process, when steps in the parser and in the navigation sections cause cache selection to occur.


Multiple application caches in different application cache groups can contain the same resource, e.g. if the manifests all reference that resource. If the user agent is to select an application cache from a list of relevant application caches that contain a resource, the user agent must use the application cache that the user most likely wants to see the resource from, taking into account the following:


A URL matches a fallback namespace if there exists a relevant application cache whose manifest's URL has the same origin as the URL in question, and that has a fallback namespace that is a prefix match for the URL being examined. If multiple fallback namespaces match the same URL, the longest one is the one that matches. A URL looking for a fallback namespace can match more than one application cache at a time, but only matches one namespace in each cache.

If a manifest https://example.com/app1/manifest declares that https://example.com/resources/images is a fallback namespace, and the user navigates to https://example.com:80/resources/images/cat.png, then the user agent will decide that the application cache identified by https://example.com/app1/manifest contains a namespace with a match for that URL.

7.9.3 キャッシュマニフェスト構文

7.9.3.1 サンプルマニフェスト

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

This example manifest requires two images and a style sheet to be cached and safelists a CGI script.

CACHE MANIFEST
# the above line is required

# this is a comment
# there can be as many of these anywhere in the file
# they are all ignored
  # comments can have spaces before them
  # but must be alone on the line

# blank lines are ignored too

# these are files that need to be cached they can either be listed
# first, or a "CACHE:" header could be put before them, as is done
# lower down.
images/sound-icon.png
images/background.png
# note that each file has to be put on its own line

# here is a file for the online safelist -- it isn't cached, and
# references to this file will bypass the cache, always hitting the
# network (or trying to, if the user is offline).
NETWORK:
comm.cgi

# here is another set of files to cache, this time just the CSS file.
CACHE:
style/default.css

同様に次のように記述することができる:

CACHE MANIFEST
NETWORK:
comm.cgi
CACHE:
style/default.css
images/sound-icon.png
images/background.png

オフラインアプリケーションキャッシュマニフェストは、絶対パスまたは絶対URLを使用することができる:

CACHE MANIFEST

/main/home
/main/app.js
/settings/home
/settings/app.js
https://img.example.com/logo.png
https://img.example.com/check.png
https://img.example.com/cross.png

次のマニフェストは、ユーザーがオフラインの間にサイト上の任意のページに表示されている汎用のエラーページを定義する。これはまた、オンラインセーフリストワイルドカードフラグopenであることを指定し、他のサイト上のリソースにアクセスがブロックされないことを意味する。(汎用フォールバック名前空間なので、同じサイト上のリソースがすでにブロックされない。)

このマニフェスト上のすべてのページのように、同じページにヒットする後続はキャッシュからすぐに読み込まれるので、それらが取得されるようにローカルでキャッシュされるだろう。マニフェストが変更されるまで、これらのページは、再度サーバーから取得されることはない。マニフェストが変更される際、次にすべてのファイルが再ダウンロードされる。

スタイルシートや画像などのようなサブリソースは、しかし、通常のHTTPキャッシングセマンティックスを使用してのみキャッシュされる。

CACHE MANIFEST
FALLBACK:
/ /offline.html
NETWORK:
*
7.9.3.2 キャッシュマニフェストの記述

マニフェストは、text/cache-manifestMIMEタイプを使用して配信しなければならない。text/cache-manifestMIMEタイプを使用して配信されるすべてのリソースは、この節で説明するように、アプリケーションキャッシュマニフェストの構文に従わなければならない。

アプリケーションキャッシュマニフェストは、テキストがUTF-8を使用してエンコードされるテキストファイルである。アプリケーションキャッシュマニフェストでのデータは行ベースである。Newlines must be represented by U+000A LINE FEED (LF) characters, U+000D CARRIAGE RETURN (CR) characters, or U+000D CARRIAGE RETURN (CR) U+000A LINE FEED (LF) pairs. [ENCODING]

これは、すべてのtext/*型が唯一のCRLF改行を許可する必要がある、RFC 2046の故意の違反である。しかし、この要件は時代遅れである。CR、LFおよびCRLFの改行の使用は一般的に支持されており、実際に時にCRLFはテキストエディターでサポートされない[RFC2046]

The first line of an application cache manifest must consist of the string "CACHE", a single U+0020 SPACE character, the string "MANIFEST", and either a U+0020 SPACE character, a U+0009 CHARACTER TABULATION (tab) character, a U+000A LINE FEED (LF) character, or a U+000D CARRIAGE RETURN (CR) character. The first line may optionally be preceded by a U+FEFF BYTE ORDER MARK (BOM) character. 他のテキストが最初の行にある場合、無視される。

後続の行がもしあれば、すべて次のいずれかでなければならない:

空白行

Blank lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters only.

コメント

Comment lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, followed by a single U+0023 NUMBER SIGN character (#), followed by zero or more characters other than U+000A LINE FEED (LF) and U+000D CARRIAGE RETURN (CR) characters.

Comments need to be on a line on their own. If they were to be included on a line with a URL, the "#" would be mistaken for part of a fragment.

セクションヘッダー

セクションヘッダーは、現在のセクションを変更する。可能な4つのセクションヘッダーが存在する:

CACHE:
明示的なセクションに切り替える。
FALLBACK:
代替セクションに切り替える。
NETWORK:
Switches to the online safelist section.
SETTINGS:
設定セクションに切り替える。

Section header lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, followed by one of the names above (including the U+003A COLON character (:)) followed by zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters.

皮肉なことに、デフォルトでは、現在のセクションは、明示的なセクションである。

現在のセクションのデータ

データ行が取得しなければならない形式は、現在のセクションに依存する。

When the current section is the explicit section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, a valid URL string identifying a resource other than the manifest itself, and then zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters.

When the current section is the fallback section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, a valid URL string identifying a resource other than the manifest itself, one or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, another valid URL string identifying a resource other than the manifest itself, and then zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters.

When the current section is the online safelist section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, either a single U+002A ASTERISK character (*) or a valid URL string identifying a resource other than the manifest itself, and then zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters.

When the current section is the settings section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, a setting, and then zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters.

現在のところ1つの設定のみが定義される:

キャッシュモード設定
これは、文字列"prefer-online"で構成される。この文字列は、キャッシュモード優先オンラインに設定する。(キャッシュモードはデフォルトで高速になる。)

設定セクション内で、各設定は1回以上出現してはならない。

マニフェストは、複数回のセクションを含んでもよい。セクションは空であってもよい。

フォールバック名前空間自体に関連付けられたフォールバックページであるURL、およびそれらの名前空間は、データ行の最初のURLである名前空間、および2番目のURLであるフォールバックページ対応する、フォールバックセクションで指定されなければならない。キャッシュされる他のすべてのページは、明示的なセクションに記載されなければならない。

フォールバック名前空間およびフォールバックエントリは、マニフェスト自身と同じ生成元を持たなければならない。Fallback namespaces must also be in the same path as the manifest's URL.

フォールバック名前空間は、複数回記載されてはならない。

ユーザーエージェントがオンラインセーフリストに入れる名前空間は、すべてオンラインセーフリストセクションで指定されなければならない。(This is needed for any URL that the page is intending to use to communicate back to the server.) To specify that all URLs are automatically safelisted in this way, a U+002A ASTERISK character (*) may be specified as one of the URLs.

Authors should not include namespaces in the online safelist for which another namespace in the online safelist is a prefix match.

相対URLはマニフェスト自身のURLを基準に指定されなければならない。マニフェスト内のすべてのURLは、(明示的または暗黙的に、相対URLを使用して)マニフェスト自身と同じschemeを持たなければならない。[URL]

URLs in manifests must not have fragments (i.e. the U+0023 NUMBER SIGN character isn't allowed in URLs in manifests).

Fallback namespaces and namespaces in the online safelist are matched by prefix match.

7.9.3.3 Parsing cache manifests

When a user agent is to parse a manifest, it means that the user agent must run the following steps:

  1. UTF-8 decode the byte stream corresponding with the manifest to be parsed.

    The UTF-8 decode algorithm strips a leading BOM, if any.

  2. Let base URL be the absolute URL representing the manifest.

  3. Apply the URL parser to base URL, and let manifest path be the path component thus obtained.

  4. Remove all the characters in manifest path after the last U+002F SOLIDUS character (/), if any. (The first character and the last character in manifest path after this step will both be slashes, the URL path separator character.)

  5. Apply the URL parser steps to the base URL, so that the components from its URL record can be used by the subsequent steps of this algorithm.

  6. Let explicit URLs be an initially empty list of absolute URLs for explicit entries.

  7. Let fallback URLs be an initially empty mapping of fallback namespaces to absolute URLs for fallback entries.

  8. Let online safelist namespaces be an initially empty list of absolute URLs for an online safelist.

  9. Let online safelist wildcard flag be blocking.

  10. Let cache mode flag be fast.

  11. Let input be the decoded text of the manifest's byte stream.

  12. Let position be a pointer into input, initially pointing at the first character.

  13. If the characters starting from position are "CACHE", followed by a U+0020 SPACE character, followed by "MANIFEST", then advance position to the next character after those. Otherwise, this isn't a cache manifest; abort this algorithm with a failure while checking for the magic signature.

  14. If the character at position is neither a U+0020 SPACE character, a U+0009 CHARACTER TABULATION (tab) character, U+000A LINE FEED (LF) character, nor a U+000D CARRIAGE RETURN (CR) character, then this isn't a cache manifest; abort this algorithm with a failure while checking for the magic signature.

  15. This is a cache manifest. The algorithm cannot fail beyond this point (though bogus lines can get ignored).

  16. Collect a sequence of code points that are not U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters from input given position, and ignore those characters. (Extra text on the first line, after the signature, is ignored.)

  17. Let mode be "explicit".

  18. Start of line: If position is past the end of input, then jump to the last step. Otherwise, collect a sequence of code points that are U+000A LINE FEED (LF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, or U+0009 CHARACTER TABULATION (tab) characters from input given position.

  19. Now, collect a sequence of code points that are not U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters from input given position, and let the result be line.

  20. Drop any trailing U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters at the end of line.

  21. If line is the empty string, then jump back to the step labeled start of line.

  22. If the first character in line is a U+0023 NUMBER SIGN character (#), then jump back to the step labeled start of line.

  23. If line equals "CACHE:" (the word "CACHE" followed by a U+003A COLON character (:)), then set mode to "explicit" and jump back to the step labeled start of line.

  24. If line equals "FALLBACK:" (the word "FALLBACK" followed by a U+003A COLON character (:)), then set mode to "fallback" and jump back to the step labeled start of line.

  25. If line equals "NETWORK:" (the word "NETWORK" followed by a U+003A COLON character (:)), then set mode to "online safelist" and jump back to the step labeled start of line.

  26. If line equals "SETTINGS:" (the word "SETTINGS" followed by a U+003A COLON character (:)), then set mode to "settings" and jump back to the step labeled start of line.

  27. If line ends with a U+003A COLON character (:), then set mode to "unknown" and jump back to the step labeled start of line.

  28. This is either a data line or it is syntactically incorrect.

  29. Let position be a pointer into line, initially pointing at the start of the string.

  30. Let tokens be a list of strings, initially empty.

  31. While position doesn't point past the end of line:

    1. Let current token be an empty string.

    2. While position doesn't point past the end of line and the character at position is neither a U+0020 SPACE nor a U+0009 CHARACTER TABULATION (tab) character, add the character at position to current token and advance position to the next character in input.

    3. Add current token to the tokens list.

    4. While position doesn't point past the end of line and the character at position is either a U+0020 SPACE or a U+0009 CHARACTER TABULATION (tab) character, advance position to the next character in input.

  32. Process tokens as follows:

    If mode is "explicit"

    Let urlRecord be the result of parsing the first item in tokens with base URL; ignore the rest.

    If urlRecord is failure, then jump back to the step labeled start of line.

    If urlRecord has a different scheme component than base URL (the manifest's URL), then jump back to the step labeled start of line.

    Let new URL be the result of applying the URL serializer algorithm to urlRecord, with the exclude fragment flag set.

    Add new URL to the explicit URLs.

    If mode is "fallback"

    Let part one be the first token in tokens, and let part two be the second token in tokens.

    Let urlRecordOne be the result of parsing part one with base URL.

    Let urlRecordTwo be the result of parsing part two with base URL.

    If either urlRecordOne or urlRecordTwo are failure, then jump back to the step labeled start of line.

    If the origin of either urlRecordOne or urlRecordTwo is not same origin with the manifest's URL origin, then jump back to the step labeled start of line.

    Let part one path be the path component of urlRecordOne.

    If manifest path is not a prefix match for part one path, then jump back to the step labeled start of line.

    Let part one be the result of applying the URL serializer algorithm to urlRecordOne, with the exclude fragment flag set.

    Let part two be the result of applying the URL serializer algorithm to urlRecordTwo, with the exclude fragment flag set.

    If part one is already in the fallback URLs mapping as a fallback namespace, then jump back to the step labeled start of line.

    Otherwise, add part one to the fallback URLs mapping as a fallback namespace, mapped to part two as the fallback entry.

    If mode is "online safelist"

    If the first item in tokens is a U+002A ASTERISK character (*), then set online safelist wildcard flag to open and jump back to the step labeled start of line.

    Otherwise, let urlRecord be the result of parsing the first item in tokens with base URL.

    If urlRecord is failure, then jump back to the step labeled start of line.

    If urlRecord has a different scheme component than base URL (the manifest's URL), then jump back to the step labeled start of line.

    Let new URL be the result of applying the URL serializer algorithm to urlRecord, with the exclude fragment flag set.

    Add new URL to the online safelist namespaces.

    If mode is "settings"

    If tokens contains a single token, and that token is a case-sensitive match for the string "prefer-online", then set cache mode flag to prefer-online and jump back to the step labeled start of line.

    Otherwise, the line is an unsupported setting: do nothing; the line is ignored.

    If mode is "unknown"

    Do nothing. The line is ignored.

  33. Jump back to the step labeled start of line. (That step jumps to the next, and last, step when the end of the file is reached.)

  34. Return the explicit URLs list, the fallback URLs mapping, the online safelist namespaces, the online safelist wildcard flag, and the cache mode flag.

The resource that declares the manifest (with the manifest attribute) will always get taken from the cache, whether it is listed in the cache or not, even if it is listed in an online safelist namespace.

If a resource is listed in the explicit section or as a fallback entry in the fallback section, the resource will always be taken from the cache, regardless of any other matching entries in the fallback namespaces or online safelist namespaces.

When a fallback namespace and an online safelist namespace overlap, the online safelist namespace has priority.

The online safelist wildcard flag is applied last, only for URLs that match neither the online safelist namespace nor the fallback namespace and that are not listed in the explicit section.

7.9.4 Downloading or updating an application cache

When the user agent is required (by other parts of this specification) to start the application cache download process for an absolute URL purported to identify a manifest, or for an application cache group, potentially given a particular cache host, and potentially given a master resource, the user agent must run the steps below. These steps are always run in parallel with the event loop tasks.

Some of these steps have requirements that only apply if the user agent shows caching progress. Support for this is optional. Caching progress UI could consist of a progress bar or message panel in the user agent's interface, or an overlay, or something else. Certain events fired during the application cache download process allow the script to override the display of such an interface. (Such events are delayed until after the load event has fired.) The goal of this is to allow Web applications to provide more seamless update mechanisms, hiding from the user the mechanics of the application cache mechanism. User agents may display user interfaces independent of this, but are encouraged to not show prominent update progress notifications for applications that cancel the relevant events.

The application cache download process steps are as follows:

  1. Optionally, wait until the permission to start the application cache download process has been obtained from the user and until the user agent is confident that the network is available. This could include doing nothing until the user explicitly opts-in to caching the site, or could involve prompting the user for permission. The algorithm might never get past this point. (This step is particularly intended to be used by user agents running on severely space-constrained devices or in highly privacy-sensitive environments).

  2. Atomically, so as to avoid race conditions, perform the following substeps:

    1. Pick the appropriate substeps:

      If these steps were invoked with an absolute URL purported to identify a manifest

      Let manifest URL be that absolute URL.

      If there is no application cache group identified by manifest URL, then create a new application cache group identified by manifest URL. Initially, it has no application caches. One will be created later in this algorithm.

      If these steps were invoked with an application cache group

      Let manifest URL be the absolute URL of the manifest used to identify the application cache group to be updated.

      If that application cache group is obsolete, then abort this instance of the application cache download process. This can happen if another instance of this algorithm found the manifest to be 404 or 410 while this algorithm was waiting in the first step above.

    2. Let cache group be the application cache group identified by manifest URL.

    3. If these steps were invoked with a master resource, then add the resource, along with the resource's Document, to cache group's list of pending master entries.

    4. If these steps were invoked with a cache host, and the status of cache group is checking or downloading, then queue a post-load task to run these steps:

      1. Let showProgress be the result of firing an event named checking at the ApplicationCache singleton of that cache host, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent is checking to see if it can download the application.

    5. If these steps were invoked with a cache host, and the status of cache group is downloading, then also queue a post-load task to run these steps:

      1. Let showProgress be the result of firing an event named downloading at the ApplicationCache singleton of that cache host, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user the application is being downloaded.

    6. If the status of the cache group is either checking or downloading, then abort this instance of the application cache download process, as an update is already in progress.

    7. Set the status of cache group to checking.

    8. For each cache host associated with an application cache in cache group, queue a post-load task run these steps:

      1. Let showProgress be the result of firing an event named checking at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent is checking for the availability of updates.

    The remainder of the steps run in parallel.

    If cache group already has an application cache in it, then this is an upgrade attempt. Otherwise, this is a cache attempt.

  3. If this is a cache attempt, then this algorithm was invoked with a cache host; queue a post-load task to run these steps:

    1. Let showProgress be the result of firing an event named checking at the ApplicationCache singleton of that cache host, with the cancelable attribute initialized to true.

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent is checking for the availability of updates.

  4. Let request be a new request whose url is manifest URL, client is null, destination is the empty string, referrer is "no-referrer", synchronous flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.

  5. Fetching the manifest: Let manifest be the result of fetching request. HTTP caching semantics should be honored for this request.

    Parse manifest's body according to the rules for parsing manifests, obtaining a list of explicit entries, fallback entries and the fallback namespaces that map to them, entries for the online safelist, and values for the online safelist wildcard flag and the cache mode flag.

    The MIME type of the resource is ignored — it is assumed to be text/cache-manifest. In the future, if new manifest formats are supported, the different types will probably be distinguished on the basis of the file signatures (for the current format, that is the "CACHE MANIFEST" string at the top of the file).

  6. If fetching the manifest fails due to a 404 or 410 response status, then run these substeps:

    1. Mark cache group as obsolete. This cache group no longer exists for any purpose other than the processing of Document objects already associated with an application cache in the cache group.

    2. Let task list be an empty list of tasks.

    3. For each cache host associated with an application cache in cache group, create a task to run these steps and append it to task list:

      1. Let showProgress be the result of firing an event named obsolete at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the application is no longer available for offline use.

    4. For each entry in cache group's list of pending master entries, create a task to run these steps and append it to task list:

      1. Let showProgress be the result of firing an event named error (not obsolete!) at the ApplicationCache singleton of the Document for this entry, if there still is one, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

    5. If cache group has an application cache whose completeness flag is incomplete, then discard that application cache.

    6. If appropriate, remove any user interface indicating that an update for this cache is in progress.

    7. Let the status of cache group be idle.

    8. For each task in task list, queue that task as a post-load task.

    9. Abort the application cache download process.

  7. Otherwise, if fetching the manifest fails in some other way (e.g. the server returns another 4xx or 5xx response, or there is a DNS error, or the connection times out, or the user cancels the download, or the parser for manifests fails when checking the magic signature), or if the server returned a redirect, then run the cache failure steps. [HTTP]

  8. If this is an upgrade attempt and the newly downloaded manifest is byte-for-byte identical to the manifest found in the newest application cache in cache group, or the response status is 304, then run these substeps:

    1. Let cache be the newest application cache in cache group.

    2. Let task list be an empty list of tasks.

    3. For each entry in cache group's list of pending master entries, wait for the resource for this entry to have either completely downloaded or failed.

      If the download failed (e.g. the server returns a 4xx or 5xx response, or there is a DNS error, the connection times out, or the user cancels the download), or if the resource is labeled with the "no-store" cache directive, then create a task to run these steps and append it to task list:

      1. Let showProgress be the result of firing an event named error at the ApplicationCache singleton of the Document for this entry, if there still is one, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

      Otherwise, associate the Document for this entry with cache; store the resource for this entry in cache, if it isn't already there, and categorize its entry as a master entry. If applying the URL parser algorithm to the resource's URL results in a URL record that has a non-null fragment component, the URL used for the entry in cache must instead be the absolute URL obtained from applying the URL serializer algorithm to the URL record with the exclude fragment flag set (application caches never include fragments).

    4. For each cache host associated with an application cache in cache group, create a task to run these steps and append it to task list:

      1. Let showProgress be the result of firing an event named noupdate at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the application is up to date.

    5. Empty cache group's list of pending master entries.

    6. If appropriate, remove any user interface indicating that an update for this cache is in progress.

    7. Let the status of cache group be idle.

    8. For each task in task list, queue that task as a post-load task.

    9. Abort the application cache download process.

  9. Let new cache be a newly created application cache in cache group. Set its completeness flag to incomplete.

  10. For each entry in cache group's list of pending master entries, associate the Document for this entry with new cache.

  11. Set the status of cache group to downloading.

  12. For each cache host associated with an application cache in cache group, queue a post-load task to run these steps:

    1. Let showProgress be the result of firing an event named downloading at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that a new version is being downloaded.

  13. Let file list be an empty list of URLs with flags.

  14. Add all the URLs in the list of explicit entries obtained by parsing manifest to file list, each flagged with "explicit entry".

  15. Add all the URLs in the list of fallback entries obtained by parsing manifest to file list, each flagged with "fallback entry".

  16. If this is an upgrade attempt, then add all the URLs of master entries in the newest application cache in cache group whose completeness flag is complete to file list, each flagged with "master entry".

  17. If any URL is in file list more than once, then merge the entries into one entry for that URL, that entry having all the flags that the original entries had.

  18. For each URL in file list, run the following steps. These steps may be run in parallel for two or more of the URLs at a time. If, while running these steps, the ApplicationCache object's abort() method sends a signal to this instance of the application cache download process algorithm, then run the cache failure steps instead.

    1. If the resource URL being processed was flagged as neither an "explicit entry" nor or a "fallback entry", then the user agent may skip this URL.

      This is intended to allow user agents to expire resources not listed in the manifest from the cache. Generally, implementors are urged to use an approach that expires lesser-used resources first.

    2. For each cache host associated with an application cache in cache group, queue a progress post-load task to run these steps:

      1. Let showProgress be the result of firing an event named progress at the ApplicationCache singleton of the cache host, using ProgressEvent, with the cancelable attribute initialized to true, the lengthComputable attribute initialized to true, the total attribute initialized to the number of files in file list, and the loaded attribute initialized to the number of files in file list that have been either downloaded or skipped so far. [XHR]

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that a file is being downloaded in preparation for updating the application.

    3. Let request be a new request whose url is URL, client is null, destination is the empty string, origin is manifest URL's origin, referrer is "no-referrer", synchronous flag is set, credentials mode is "include", use-URL-credentials flag is set, and redirect mode is "manual".

    4. Fetch request. If this is an upgrade attempt, then use the newest application cache in cache group as an HTTP cache, and honor HTTP caching semantics (such as expiration, ETags, and so forth) with respect to that cache. User agents may also have other caches in place that are also honored.

    5. If the previous step fails (e.g. the server returns a 4xx or 5xx response, or there is a DNS error, or the connection times out, or the user cancels the download), or if the server returned a redirect, or if the resource is labeled with the "no-store" cache directive, then run the first appropriate step from the following list: [HTTP]

      If the URL being processed was flagged as an "explicit entry" or a "fallback entry"

      If these steps are being run in parallel for any other URLs in file list, then abort these steps for those other URLs. Run the cache failure steps.

      Redirects are fatal because they are either indicative of a network problem (e.g. a captive portal); or would allow resources to be added to the cache under URLs that differ from any URL that the networking model will allow access to, leaving orphan entries; or would allow resources to be stored under URLs different than their true URLs. All of these situations are bad.

      If the error was a 404 or 410 HTTP response
      If the resource was labeled with the "no-store" cache directive

      Skip this resource. It is dropped from the cache.

      そうでなければ

      Copy the resource and its metadata from the newest application cache in cache group whose completeness flag is complete, and act as if that was the fetched resource, ignoring the resource obtained from the network.

      User agents may warn the user of these errors as an aid to development.

      These rules make errors for resources listed in the manifest fatal, while making it possible for other resources to be removed from caches when they are removed from the server, without errors, and making non-manifest resources survive server-side errors.

      Except for the "no-store" directive, HTTP caching rules that would cause a file to be expired or otherwise not cached are ignored for the purposes of the application cache download process.

    6. Otherwise, the fetching succeeded. Store the resource in the new cache.

      If the user agent is not able to store the resource (e.g. because of quota restrictions), the user agent may prompt the user or try to resolve the problem in some other manner (e.g. automatically pruning content in other caches). If the problem cannot be resolved, the user agent must run the cache failure steps.

    7. If the URL being processed was flagged as an "explicit entry" in file list, then categorize the entry as an explicit entry.

    8. If the URL being processed was flagged as a "fallback entry" in file list, then categorize the entry as a fallback entry.

    9. If the URL being processed was flagged as an "master entry" in file list, then categorize the entry as a master entry.

    10. As an optimization, if the resource is an HTML or XML file whose document element is an html element with a manifest attribute whose value doesn't match the manifest URL of the application cache being processed, then the user agent should mark the entry as being foreign.

  19. For each cache host associated with an application cache in cache group, queue a progress post-load task to run these steps:

    1. Let showProgress be the result of firing an event named progress at the ApplicationCache singleton of the cache host, using ProgressEvent, with the cancelable attribute initialized to true, the lengthComputable attribute initialized to true, and the total and loaded attributes initialized to the number of files in file list. [XHR]

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that all the files have been downloaded.

  20. Store the list of fallback namespaces, and the URLs of the fallback entries that they map to, in new cache.

  21. Store the URLs that form the new online safelist in new cache.

  22. Store the value of the new online safelist wildcard flag in new cache.

  23. Store the value of the new cache mode flag in new cache.

  24. For each entry in cache group's list of pending master entries, wait for the resource for this entry to have either completely downloaded or failed.

    If the download failed (e.g. the server returns a 4xx or 5xx response, or there is a DNS error, the connection times out, or the user cancels the download), or if the resource is labeled with the "no-store" cache directive, then run these substeps:

    1. Unassociate the Document for this entry from new cache.

    2. Queue a post-load task to run these steps:

      1. Let showProgress be the result of firing an event named error at the ApplicationCache singleton of the Document for this entry, if there still is one, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

    3. If this is a cache attempt and this entry is the last entry in cache group's list of pending master entries, then run these further substeps:

      1. Discard cache group and its only application cache, new cache.

      2. If appropriate, remove any user interface indicating that an update for this cache is in progress.

      3. Abort the application cache download process.

    4. Otherwise, remove this entry from cache group's list of pending master entries.

    Otherwise, store the resource for this entry in new cache, if it isn't already there, and categorize its entry as a master entry.

  25. Let request be a new request whose url is manifest URL, client is null, destination is the empty string, referrer is "no-referrer", synchronous flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.

  26. Let second manifest be the result of fetching request. HTTP caching semantics should again be honored for this request.

    Since caching can be honored, authors are encouraged to avoid setting the cache headers on the manifest in such a way that the user agent would simply not contact the network for this second request; otherwise, the user agent would not notice if the cache had changed during the cache update process.

  27. If the previous step failed for any reason, or if the fetching attempt involved a redirect, or if second manifest and manifest are not byte-for-byte identical, then schedule a rerun of the entire algorithm with the same parameters after a short delay, and run the cache failure steps.

  28. Otherwise, store manifest in new cache, if it's not there already, and categorize its entry as the manifest.

  29. Set the completeness flag of new cache to complete.

  30. Let task list be an empty list of tasks.

  31. If this is a cache attempt, then for each cache host associated with an application cache in cache group, create a task to run these steps and append it to task list:

    1. Let showProgress be the result of firing an event named cached at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the application has been cached and that they can now use it offline.

    Otherwise, it is an upgrade attempt. For each cache host associated with an application cache in cache group, create a task to run these steps and append it to task list:

    1. Let showProgress be the result of firing an event named updateready at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that a new version is available and that they can activate it by reloading the page.

  32. If appropriate, remove any user interface indicating that an update for this cache is in progress.

  33. Set the update status of cache group to idle.

  34. For each task in task list, queue that task as a post-load task.

The cache failure steps are as follows:

  1. Let task list be an empty list of tasks.

  2. For each entry in cache group's list of pending master entries, run the following further substeps. These steps may be run in parallel for two or more entries at a time.

    1. Wait for the resource for this entry to have either completely downloaded or failed.

    2. Unassociate the Document for this entry from its application cache, if it has one.

    3. Create a task to run these steps and append it to task list:

      1. Let showProgress be the result of firing an event named error at the ApplicationCache singleton of the Document for this entry, if there still is one, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

  3. For each cache host still associated with an application cache in cache group, create a task to run these steps and append it to task list:

    1. Let showProgress be the result of firing an event named error at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

  4. Empty cache group's list of pending master entries.

  5. If cache group has an application cache whose completeness flag is incomplete, then discard that application cache.

  6. If appropriate, remove any user interface indicating that an update for this cache is in progress.

  7. Let the status of cache group be idle.

  8. If this was a cache attempt, discard cache group altogether.

  9. For each task in task list, queue that task as a post-load task.

  10. Abort the application cache download process.

Attempts to fetch resources as part of the application cache download process may be done with cache-defeating semantics, to avoid problems with stale or inconsistent intermediary caches.


User agents may invoke the application cache download process, in the background, for any application cache group, at any time (with no cache host). This allows user agents to keep caches primed and to update caches even before the user visits a site.


Each Document has a list of pending application cache download process tasks that is used to delay events fired by the algorithm above until the document's load event has fired. When the Document is created, the list must be empty.

When the steps above say to queue a post-load task task, where task is a task that dispatches an event on a target ApplicationCache object target, the user agent must run the appropriate steps from the following list:

If target's node document is ready for post-load tasks

Queue the task task.

そうでなければ

Add task to target's node document's list of pending application cache download process tasks.

When the steps above say to queue a progress post-load task task, where task is a task that dispatches an event on a target ApplicationCache object target, the user agent must run the following steps:

  1. If there is a task in target's node document's list of pending application cache download process tasks that is labeled as a progress task, then remove that task from the list.

  2. Label task as a progress task.

  3. Queue a post-load task task.

The task source for these tasks is the networking task source.

7.9.5 The application cache selection algorithm

When the application cache selection algorithm algorithm is invoked with a Document document and optionally a manifest URL manifest URL, the user agent must run the first applicable set of steps from the following list:

If there is a manifest URL, and document was loaded from an application cache, and the URL of the manifest of that cache's application cache group is not the same as manifest URL

Mark the entry for the resource from which document was taken in the application cache from which it was loaded as foreign.

Restart the current navigation from the top of the navigation algorithm, undoing any changes that were made as part of the initial load (changes can be avoided by ensuring that the step to update the session history with the new page is only ever completed after this application cache selection algorithm is run, though this is not required).

The navigation will not result in the same resource being loaded, because "foreign" entries are never picked during navigation.

User agents may notify the user of the inconsistency between the cache manifest and the document's own metadata, to aid in application development.

If document was loaded from an application cache, and that application cache still exists (it is not now obsolete)

Associate document with the application cache from which it was loaded. Invoke, in the background, the application cache download process for that application cache's application cache group, with document as the cache host.

If document was loaded using `GET`, and, there is a manifest URL, and manifest URL has the same origin as document

Invoke, in the background, the application cache download process for manifest URL, with document as the cache host and with the resource from which document was parsed as the master resource.

If there are relevant application caches that are identified by a URL with the same origin as the URL of document, and that have this URL as one of their entries, excluding entries marked as foreign, then the user agent should use the most appropriate application cache of those that match as an HTTP cache for any subresource loads. User agents may also have other caches in place that are also honored.

そうでなければ

The Document is not associated with any application cache.

If there was a manifest URL, the user agent may report to the user that it was ignored, to aid in application development.

7.9.6 Changes to the networking model

If "AppCache" is not removed as a feature this section needs to be integrated into the Fetch standard.

When a cache host is associated with an application cache whose completeness flag is complete, any and all loads for resources related to that cache host other than those for child browsing contexts must go through the following steps instead of immediately invoking the mechanisms appropriate to that resource's scheme:

  1. If the resource is not to be fetched using the GET method, or if applying the URL parser algorithm to both its URL and the application cache's manifest's URL results in two URL records with different scheme components, then fetch the resource normally and abort these steps.

  2. If the resource's URL is a master entry, the manifest, an explicit entry, or a fallback entry in the application cache, then get the resource from the cache (instead of fetching it), and abort these steps.

  3. If there is an entry in the application cache's online safelist that has the same origin as the resource's URL and that is a prefix match for the resource's URL, then fetch the resource normally and abort these steps.

  4. If the resource's URL has the same origin as the manifest's URL, and there is a fallback namespace f in the application cache that is a prefix match for the resource's URL, then:

    Fetch the resource normally. If this results in a redirect to a resource with another origin (indicative of a captive portal), or a 4xx or 5xx status code, or if there were network errors (but not if the user canceled the download), then instead get, from the cache, the resource of the fallback entry corresponding to the fallback namespace f. Abort these steps.

  5. If the application cache's online safelist wildcard flag is open, then fetch the resource normally and abort these steps.

  6. Fail the resource load as if there had been a generic network error.

The above algorithm ensures that so long as the online safelist wildcard flag is blocking, resources that are not present in the manifest will always fail to load (at least, after the application cache has been primed the first time), making the testing of offline applications simpler.

7.9.7 Expiring application caches

As a general rule, user agents should not expire application caches, except on request from the user, or after having been left unused for an extended period of time.

Application caches and cookies have similar implications with respect to privacy (e.g. if the site can identify the user when providing the cache, it can store data in the cache that can be used for cookie resurrection). Implementors are therefore encouraged to expose application caches in a manner related to HTTP cookies, allowing caches to be expunged together with cookies and other origin-specific data.

For example, a user agent could have a "delete site-specific data" feature that clears all cookies, application caches, local storage, databases, etc, from an origin all at once.

7.9.8 Disk space

User agents should consider applying constraints on disk usage of application caches, and care should be taken to ensure that the restrictions cannot be easily worked around using subdomains.

User agents should allow users to see how much space each domain is using, and may offer the user the ability to delete specific application caches.

For predictability, quotas should be based on the uncompressed size of data stored.

How quotas are presented to the user is not defined by this specification. User agents are encouraged to provide features such as allowing a user to indicate that certain sites are trusted to use more than the default quota, e.g. by presenting a non-modal user interface while a cache is being updated, or by having an explicit safelist in the user agent's configuration interface.

7.9.9 Security concerns with offline applications caches

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

The main risk introduced by offline application caches is that an injection attack can be elevated into persistent site-wide page replacement. This attack involves using an injection vulnerability to upload two files to the victim site. The first file is an application cache manifest consisting of just a fallback entry pointing to the second file, which is an HTML page whose manifest is declared as that first file. Once the user has been directed to that second file, all subsequent accesses to any file covered by the given fallback namespace while either the user or the site is offline will instead show that second file. Targeted denial-of-service attacks or cookie bombing attacks (where the client is made to send so many cookies that the server refuses to process the request) can be used to ensure that the site appears offline.

To mitigate this, manifests can only specify fallbacks that are in the same path as the manifest itself. This means that a content injection upload vulnerability in a particular directory on a server can only be escalated to a take-over of that directory and its subdirectories. If there is no way to inject a file into the root directory, the entire site cannot be taken over.

If a site has been attacked in this way, simply removing the offending manifest might eventually clear the problem, since the next time the manifest is updated, a 404 error will be seen, and the user agent will clear the cache. "Eventually" is the key word here, however; while the attack on the user or server is ongoing, such that connections from an affected user to the affected site are blocked, the user agent will simply assume that the user is offline and will continue to use the hostile manifest. Unfortunately, if a cookie bombing attack has also been used, merely removing the manifest is insufficient; in addition, the server has to be configured to return a 404 or 410 response instead of the 413 "Request Entity Too Large" response.

TLS does not inherently protect a site from this attack, since the attack relies on content being served from the server itself. Not using application caches also does not prevent this attack, since the attack relies on an attacker-provided manifest.

7.9.10 アプリケーションキャッシュAPI

interface ApplicationCache : EventTarget {

  // update status
  const unsigned short UNCACHED = 0;
  const unsigned short IDLE = 1;
  const unsigned short CHECKING = 2;
  const unsigned short DOWNLOADING = 3;
  const unsigned short UPDATEREADY = 4;
  const unsigned short OBSOLETE = 5;
  readonly attribute unsigned short status;

  // updates
  void update();
  void abort();
  void swapCache();

  // events
  attribute EventHandler onchecking;
  attribute EventHandler onerror;
  attribute EventHandler onnoupdate;
  attribute EventHandler ondownloading;
  attribute EventHandler onprogress;
  attribute EventHandler onupdateready;
  attribute EventHandler oncached;
  attribute EventHandler onobsolete;
};
cache = window . applicationCache

Returns the ApplicationCache object that applies to the active document of that Window.

cache . status

以下に定義された定数で与えられるように、アプリケーションキャッシュの現在のステータスを返す。

cache . update()

アプリケーションキャッシュのダウンロードプロセスを起動する。

Throws an "InvalidStateError" DOMException if there is no application cache to update.

ユーザーエージェントは通常、自動的にアプリケーションキャッシュを更新する処理をするので、通常このメソッドを呼び出す必要はない。

このメソッドは、長期のアプリケーションのような状況で役立つ。たとえば、ウェブメールアプリケーションは一度に何週間もブラウザータブで開いたままかもしれない。このようなアプリケーションは、毎日更新をテストできるだろう。

cache . abort()

アプリケーションキャッシュのダウンロード処理を中止する。

このメソッドは、(帯域幅が限られるためなどで)ユーザーが更新を停止したい場合に、独自のキャッシング進捗UIを表示するウェブアプリケーションで使用されることを意図する。

cache . swapCache()

新しいものが存在する場合、最新のアプリケーションキャッシュに切り替わる。If there isn't, throws an "InvalidStateError" DOMException.

これは、以前にロードされたリソースが再読み込みされることはない。たとえば、画像が急にリロードされないと、スタイルシートやスクリプトが再解析または再評価されない。唯一の変更点は、キャッシュされたリソースに対する後続の要求が新しいコピーを取得することである。

このメソッドが呼び出される前にupdatereadyイベントが発火する。一度発火すると、ウェブアプリケーションは、その余暇で、より最近のアップデートで一つに基礎となるキャッシュを切り替えるためにこのメソッドを呼び出す。これを適切に使うためには、アプリケーションは動作に新しい機能をもたらすことができるようにする必要がある。たとえば、新しい機能を有効にするためにスクリプトをリロードするなど。

swapCache()の代替は、location.reload()を使用して、ユーザーに適した時点で単にページ全体をリロードすることである。

There is a one-to-one mapping from cache hosts to ApplicationCache objects. The applicationCache attribute on Window objects must return the ApplicationCache object associated with the Window object's active document.

A Document has an associated ApplicationCache object even if that cache host has no actual application cache.


The status attribute, on getting, must return the current state of the application cache that the ApplicationCache object's cache host is associated with, if any. This must be the appropriate value from the following list:

UNCACHED(数値0)

ApplicationCacheオブジェクトのキャッシュホストは、この時点でアプリケーションキャッシュに関連付けられていない。

IDLE(数値1)

ApplicationCacheオブジェクトのキャッシュホストは、アプリケーションキャッシュグループ更新ステータスidleであるアプリケーションキャッシュに関連付けられ、そのアプリケーションキャッシュは、そのアプリケーションキャッシュグループ最新のキャッシュであり、アプリケーションキャッシュグループは、obsoleteとマークされない。

CHECKING(数値2)

ApplicationCacheオブジェクトのキャッシュホストは、アプリケーションキャッシュグループ更新ステータスcheckingであるアプリケーションキャッシュに関連付けられる。

DOWNLOADING(数値3)

ApplicationCacheオブジェクトのキャッシュホストは、アプリケーションキャッシュグループ更新ステータスdownloadingであるアプリケーションキャッシュに関連付けられる。

UPDATEREADY(数値4)

ApplicationCacheオブジェクトのキャッシュホストは、アプリケーションキャッシュグループ更新ステータスidleであるアプリケーションキャッシュに関連付けられ、そのアプリケーションキャッシュグループobsoleteとしてマークされないが、そのアプリケーションキャッシュは、そのグループ内の最新のキャッシュではない

OBSOLETE(数値5)

ApplicationCacheオブジェクトのキャッシュホストは、アプリケーションキャッシュグループobsoleteとマークされるアプリケーションキャッシュに関連付けられる。


If the update() method is invoked, the user agent must invoke the application cache download process, in the background, for the application cache group of the application cache with which the ApplicationCache object's cache host is associated, but without giving that cache host to the algorithm. If there is no such application cache, or if its application cache group is marked as obsolete, then the method must throw an "InvalidStateError" DOMException instead.

If the abort() method is invoked, the user agent must send a signal to the current application cache download process for the application cache group of the application cache with which the ApplicationCache object's cache host is associated, if any. If there is no such application cache, or it does not have a current application cache download process, then do nothing.

If the swapCache() method is invoked, the user agent must run the following steps:

  1. Check that ApplicationCache object's cache host is associated with an application cache. If it is not, then throw an "InvalidStateError" DOMException and abort these steps.

  2. Let cache be the application cache with which the ApplicationCache object's cache host is associated. (By definition, this is the same as the one that was found in the previous step.)

  3. If cache's application cache group is marked as obsolete, then unassociate the ApplicationCache object's cache host from cache and abort these steps. (Resources will now load from the network instead of the cache.)

  4. Check that there is an application cache in the same application cache group as cache whose completeness flag is complete and that is newer than cache. If there is not, then throw an "InvalidStateError" DOMException exception and abort these steps.

  5. Let new cache be the newest application cache in the same application cache group as cache whose completeness flag is complete.

  6. Unassociate the ApplicationCache object's cache host from cache and instead associate it with new cache.

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the ApplicationCache interface:

イベントハンドラー イベントハンドラーイベント型
onchecking checking
onerror error
onnoupdate noupdate
ondownloading downloading
onprogress progress
onupdateready updateready
oncached cached
onobsolete obsolete

Support: online-statusChrome for Android 56+Chrome 14+iOS Safari 4.2+UC Browser for Android (limited) 11+Firefox 41+IE 9+Samsung Internet 4+Opera Mini NoneAndroid Browser 2.3+Safari 5+Edge 12+Opera 15+

Source: caniuse.com

[NoInterfaceObject, Exposed=(Window,Worker)]
interface NavigatorOnLine {
  readonly attribute boolean onLine;
};
window . navigator . onLine

ユーザーエージェントが正確にオフラインである(ネットワークから切断されている)場合にfalseを返すユーザーエージェントがオンラインかもしれない場合にtrueを返す。

この属性値が変更される場合、イベントonlineおよびofflineが発火する。

The navigator.onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail), and must return true otherwise.

When the value that would be returned by the navigator.onLine attribute of a Window or WorkerGlobalScope changes from true to false, the user agent must queue a task to fire an event named offline at the Window or WorkerGlobalScope object.

On the other hand, when the value that would be returned by the navigator.onLine attribute of a Window or WorkerGlobalScope changes from false to true, the user agent must queue a task to fire an event named online at the Window or WorkerGlobalScope object.

The task source for these tasks is the networking task source.

この属性は、本質的に信頼できない。コンピューターは、インターネット接続がなくてもネットワークに接続できる。

この例において、ブラウザーがオンラインおよびオフラインになるように、インジケーターが更新される。

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Online status</title>
  <script>
   function updateIndicator() {
     document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline';
   }
  </script>
 </head>
 <body onload="updateIndicator()" ononline="updateIndicator()" onoffline="updateIndicator()">
  <p>The network is: <span id="indicator">(state unknown)</span>
 </body>
</html>