1. 8.4 動的マークアップの挿入
      1. 8.4.1 入力ストリームを開く
      2. 8.4.2 入力ストリームを閉じる
      3. 8.4.3 document.write()
      4. 8.4.4 document.writeln()
    2. 8.5 DOM解析およびシリアライゼーションAPI
      1. 8.5.1 DOMParserインターフェイス
      2. 8.5.2 HTML解析および挿入メソッド
      3. 8.5.3 HTML streaming methods
      4. 8.5.4 HTML serialization methods
      5. 8.5.5 The innerHTML property
      6. 8.5.6 The outerHTML property
      7. 8.5.7 The insertAdjacentHTML() method
      8. 8.5.8 The createContextualFragment() method
      9. 8.5.9 The XMLSerializer interface
    3. 8.6 HTMLサニタイゼーション
      1. 8.6.1 導入
        1. 8.6.1.1 安全および安全でない
      2. 8.6.2 Sanitizerインターフェイス
      3. 8.6.3 サニタイザーの設定
        1. 8.6.3.1 設定の不変条件
      4. 8.6.4 Sanitization algorithms
      5. 8.6.5 サニタイゼーション定数
      6. 8.6.6 セキュリティの考慮事項
        1. 8.6.6.1 サーバー側で反映および保存されたXSS
        2. 8.6.6.2 DOMクローバリング
        3. 8.6.6.3 スクリプトガジェットを使用するXSS
        4. 8.6.6.4 ミューテーションXSS

8.4 動的マークアップの挿入

マークアップを文書に動的に挿入するためのAPIはパーサーと相互作用するため、その動作は、HTML文書(およびHTMLパーサー)かXML文書(およびXMLパーサー)かのどちらで使用されるかによって異なる。

Document objects have a throw-on-dynamic-markup-insertion counter, which is used in conjunction with the create an element for the token algorithm to prevent custom element constructors from being able to use document.open(), document.close(), and document.write() when they are invoked by the parser. Initially, the counter must be set to zero.

8.4.1 入力ストリームを開く

document = document.open()

Document/open

Support in all current engines.

Firefox1+Safari11+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

前のオブジェクトを再利用する場合を除き、あたかもそれが新しいDocumentオブジェクトであるかのように、Documentに正しい場所で置換され、その後返される。

結果として得られるDocumentはHTMLパーサーが関連付けられており、 document.write()を使用して解析するデータを与えることができる。

Documentがまだ解析されている場合、メソッドは効果がない。

DocumentがXML文書である場合、"InvalidStateError" DOMExceptionを投げる。

パーサーがカスタム要素コンストラクターを現在実行している場合、"InvalidStateError" DOMExceptionを投げる。

window = document.open(url, name, features)

window.open()メソッドのように動作する。

Document objects have an active parser was aborted boolean, which is used to prevent scripts from invoking the document.open() and document.write() methods (directly or indirectly) after the document's active parser has been aborted. 最初はfalseである。

The document open steps, given a document, are as follows:

  1. If document is an XML document, then throw an "InvalidStateError" DOMException.

  2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.

  3. Let entryDocument be the entry global object's associated Document.

  4. If document's origin is not same origin to entryDocument's origin, then throw a "SecurityError" DOMException.

  5. If document has an active parser whose script nesting level is greater than 0, then return document.

    This basically causes document.open() to be ignored when it's called in an inline script found during parsing, while still letting it have an effect when called from a non-parser task such as a timer callback or event handler.

  6. Similarly, if document's unload counter is greater than 0, then return document.

    This basically causes document.open() to be ignored when it's called from a beforeunload, pagehide, or unload event handler while the Document is being unloaded.

  7. If document's active parser was aborted is true, then return document.

    This notably causes document.open() to be ignored if it is called after a navigation has started, but only during the initial parse. See issue #4723 for more background.

  8. If document's node navigable is non-null and document's node navigable's ongoing navigation is a navigation ID, then stop loading document's node navigable.

  9. For each shadow-including inclusive descendant node of document, erase all event listeners and handlers given node.

  10. If document is the associated Document of document's relevant global object, then erase all event listeners and handlers given document's relevant global object.

  11. Replace all with null within document.

  12. If document is fully active:

    1. Let newURL be a copy of entryDocument's URL.

    2. If entryDocument is not document, then set newURL's fragment to null.

    3. Run the URL and history update steps with document and newURL.

  13. Set document's is initial about:blank to false.

  14. If document's iframe load in progress flag is set, then set document's mute iframe load flag.

  15. Set document to no-quirks mode.

  16. Create an HTML parser whose allow declarative shadow roots is document's allow declarative shadow roots, and associate it with document. This is a script-created parser (meaning that it can be closed by the document.open() and document.close() methods, or by closing the stream when streaming HTML, and that the tokenizer will wait for an explicit call to document.close() or for the stream to be closed before emitting an end-of-file token). The encoding confidence is irrelevant.

  17. Set the insertion point to point at just before the end of the input stream (which at this point will be empty).

  18. Update the current document readiness of document to "loading".

    This causes a readystatechange event to fire, but the event is actually unobservable to author code, because of the previous step which erased all event listeners and handlers that could observe it.

  19. Return document.

The document open steps do not affect whether a Document is ready for post-load tasks or completely loaded.

The open(unused1, unused2) method must return the result of running the document open steps with this.

The unused1 and unused2 arguments are ignored, but kept in the IDL to allow code that calls the function with one or two arguments to continue working. They are necessary due to Web IDL overload resolution algorithm rules, which would throw a TypeError exception for such calls had the arguments not been there. whatwg/webidl issue #581 investigates changing the algorithm to allow for their removal. [WEBIDL]

The open(url, name, features) method must run these steps:

  1. If this is not fully active, then throw an "InvalidAccessError" DOMException.

  2. Return the result of running the window open steps with url, name, and features.

8.4.2 入力ストリームを閉じる

document.close()

Document/close

Support in all current engines.

Firefox1+Safari11+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

document.open()メソッドによって開かれた入力ストリームを閉じる。

DocumentがXML文書である場合、"InvalidStateError" DOMExceptionを投げる。

パーサーがカスタム要素コンストラクターを現在実行している場合、"InvalidStateError" DOMExceptionを投げる。

The close() method must run the following steps:

  1. If this is an XML document, then throw an "InvalidStateError" DOMException.

  2. If this's throw-on-dynamic-markup-insertion counter is greater than zero, then throw an "InvalidStateError" DOMException.

  3. If there is no script-created parser associated with this, then return.

  4. Insert an explicit "EOF" character at the end of the parser's input stream.

  5. If this's pending parsing-blocking script is not null, then return.

  6. Run the tokenizer, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the explicit "EOF" character or spins the event loop.

8.4.3 document.write()

document.write(...text)

Document/write

Support in all current engines.

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

一般に、与えられた文字列をDocumentの入力ストリームに加える。

このメソッドは非常に特異な振る舞いを持つ。一部の場合において、このメソッドは、パーサーが実行されている間、HTMLパーサーの状態に影響を与えることができる。その結果、文書のソースに対応しないDOMをもたらす(たとえば、記述された文字列が、文字列"<plaintext>"または"<!--"である場合)。他の例では、あたかもdocument.open()が呼び出されていたかのように、呼び出しが最初に現在のページをクリアできる。さらに多くの例では、メソッドは単に無視されるか、または例外を投げる。User agents are explicitly allowed to avoid executing script elements inserted via this method. さらに悪いことに、このメソッドの正確な動作は、場合によってはネットワーク遅延に依存する可能性があり、これはデバッグが非常に困難な障害につながる可能性がある。これらすべての理由から、このメソッドの使用は強く勧めない。

XML文書で呼び出されるとき、"InvalidStateError" DOMExceptionを投げる。

パーサーがカスタム要素コンストラクターを現在実行している場合、"InvalidStateError" DOMExceptionを投げる。

このメソッドは、scriptまたはイベントハンドラーコンテンツ属性のような潜在的に危険な要素および属性を削除するためのサニタイズを実行しない。

Document objects have an ignore-destructive-writes counter, which is used in conjunction with the processing of script elements to prevent external scripts from being able to use document.write() to blow away the document by implicitly calling document.open(). Initially, the counter must be set to zero.

The document write steps, given a Document object document, a list text, a boolean lineFeed, and a string sink, are as follows:

  1. Let string be the empty string.

  2. Let isTrusted be false if text contains a string; otherwise true.

  3. For each value of text:

    1. If value is a TrustedHTML object, then append value's associated data to string.

    2. Otherwise, append value to string.

  4. If isTrusted is false, set string to the result of invoking the get trusted type compliant string algorithm with TrustedHTML, this's relevant global object, string, sink, and "script".

  5. If lineFeed is true, append U+000A LINE FEED to string.

  6. If document is an XML document, then throw an "InvalidStateError" DOMException.

  7. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.

  8. If document's active parser was aborted is true, then return.

  9. If the insertion point is undefined:

    1. If document's unload counter is greater than 0 or document's ignore-destructive-writes counter is greater than 0, then return.

    2. Run the document open steps with document.

  10. Insert string into the input stream just before the insertion point.

  11. If document's pending parsing-blocking script is null, then have the HTML parser process string, one code point at a time, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the insertion point or when the processing of the tokenizer is aborted by the tree construction stage (this can happen if a script end tag token is emitted by the tokenizer), and then flush pending text.

    If the document.write() method was called from script executing inline (i.e. executing because the parser parsed a set of script tags), then this is a reentrant invocation of the parser. If the parser pause flag is set, the tokenizer will abort immediately and no HTML will be parsed, per the tokenizer's parser pause flag check.

The document.write(...text) method steps are to run the document write steps with this, text, false, and "Document write".

8.4.4 document.writeln()

document.writeln(...text)

Document/writeln

Support in all current engines.

Firefox1+Safari11+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android47+

改行文字の後に、与えられた文字列をDocumentの入力ストリームに加える。必要ならば、open()メソッドを暗黙のうちに最初に呼び出す。

このメソッドは非常に特異な振る舞いを持つ。Use of this method is strongly discouraged, for the same reasons as document.write().

XML文書で呼び出されるとき、"InvalidStateError" DOMExceptionを投げる。

パーサーがカスタム要素コンストラクターを現在実行している場合、"InvalidStateError" DOMExceptionを投げる。

このメソッドは、scriptまたはイベントハンドラーコンテンツ属性のような潜在的に危険な要素および属性を削除するためのサニタイズを実行しない。

The document.writeln(...text) method steps are to run the document write steps with this, text, true, and "Document writeln".

8.5 DOM解析およびシリアライゼーションAPI

DOMParser

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android?Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android10.1+
partial interface Element {
  [CEReactions] undefined setHTML(DOMString html, optional SetHTMLOptions options = {});
  [CEReactions] undefined appendHTML(DOMString html, optional SetHTMLOptions options = {});
  [CEReactions] undefined prependHTML(DOMString html, optional SetHTMLOptions options = {});
  [CEReactions, NewObject] WritableStream streamHTML(optional SetHTMLOptions options = {});
  [NewObject] WritableStream streamAppendHTML(optional SetHTMLOptions options = {});
  [NewObject] WritableStream streamPrependHTML(optional SetHTMLOptions options = {});
  [CEReactions] undefined setHTMLUnsafe((TrustedHTML or DOMString) html, optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [CEReactions] undefined appendHTMLUnsafe((TrustedHTML or DOMString) html, optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [CEReactions] undefined prependHTMLUnsafe((TrustedHTML or DOMString) html, optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [CEReactions, NewObject] WritableStream streamHTMLUnsafe(optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [NewObject] WritableStream streamAppendHTMLUnsafe(optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [NewObject] WritableStream streamPrependHTMLUnsafe(optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  DOMString getHTML(optional GetHTMLOptions options = {});

  [CEReactions] attribute (TrustedHTML or [LegacyNullToEmptyString] DOMString) innerHTML;
  [CEReactions] attribute (TrustedHTML or [LegacyNullToEmptyString] DOMString) outerHTML;
  [CEReactions] undefined insertAdjacentHTML(DOMString position, (TrustedHTML or DOMString) string);
};

partial interface ShadowRoot {
  [CEReactions] undefined setHTML(DOMString html, optional SetHTMLOptions options = {});
  [CEReactions] undefined appendHTML(DOMString html, optional SetHTMLOptions options = {});
  [CEReactions] undefined prependHTML(DOMString html, optional SetHTMLOptions options = {});
  [CEReactions, NewObject] WritableStream streamHTML(optional SetHTMLOptions options = {});
  [NewObject] WritableStream streamAppendHTML(optional SetHTMLOptions options = {});
  [NewObject] WritableStream streamPrependHTML(optional SetHTMLOptions options = {});
  [CEReactions] undefined setHTMLUnsafe((TrustedHTML or DOMString) html, optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [CEReactions] undefined appendHTMLUnsafe((TrustedHTML or DOMString) html, optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [CEReactions] undefined prependHTMLUnsafe((TrustedHTML or DOMString) html, optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [CEReactions, NewObject] WritableStream streamHTMLUnsafe(optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [NewObject] WritableStream streamAppendHTMLUnsafe(optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [NewObject] WritableStream streamPrependHTMLUnsafe(optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  DOMString getHTML(optional GetHTMLOptions options = {});

  [CEReactions] attribute (TrustedHTML or [LegacyNullToEmptyString] DOMString) innerHTML;
};

partial interface mixin NonDocumentTypeChildNode {
  [CEReactions] undefined beforeHTML(DOMString html, optional SetHTMLOptions options = {});
  [CEReactions] undefined afterHTML(DOMString html, optional SetHTMLOptions options = {});
  [CEReactions] undefined replaceWithHTML(DOMString html, optional SetHTMLOptions options = {});
  [NewObject] WritableStream streamBeforeHTML(optional SetHTMLOptions options = {});
  [NewObject] WritableStream streamAfterHTML(optional SetHTMLOptions options = {});
  [CEReactions, NewObject] WritableStream streamReplaceWithHTML(optional SetHTMLOptions options = {});
  [CEReactions] undefined beforeHTMLUnsafe((TrustedHTML or DOMString) html, optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [CEReactions] undefined afterHTMLUnsafe((TrustedHTML or DOMString) html, optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [CEReactions] undefined replaceWithHTMLUnsafe((TrustedHTML or DOMString) html, optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [NewObject] WritableStream streamBeforeHTMLUnsafe(optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [NewObject] WritableStream streamAfterHTMLUnsafe(optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
  [CEReactions, NewObject] WritableStream streamReplaceWithHTMLUnsafe(optional (SetHTMLUnsafeOptions or TrustedHTMLParserOptions) options = {});
};

enum SanitizerPresets { "default" };
dictionary SetHTMLOptions {
  (Sanitizer or SanitizerConfig or SanitizerPresets) sanitizer = "default";
};
dictionary SetHTMLUnsafeOptions {
  (Sanitizer or SanitizerConfig or SanitizerPresets) sanitizer;
  boolean runScripts = false;
};
dictionary ParseHTMLUnsafeOptions {
  (Sanitizer or SanitizerConfig or SanitizerPresets) sanitizer;
};

dictionary GetHTMLOptions {
  boolean serializableShadowRoots = false;
  sequence<ShadowRoot> shadowRoots = [];
};

8.5.1 DOMParserインターフェイス

DOMParser インターフェイスは、HTMLまたはXMLのいずれかとして、文字列を解析することで新しいDocumentオブジェクトを作成することを可能にする。

parser = new DOMParser()

DOMParser/DOMParser

Support in all current engines.

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

新しいDOMParserオブジェクトを構築する。

document = parser.parseFromString(string, type)

DOMParser/parseFromString

Support in all current engines.

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

typeに応じて、HTMLまたはXMLパーサーのいずれかを使用して文字列を解析し、結果のDocumentを返す。typeは、"text/html"(HTMLパーサーを呼び出す)、または"text/xml"、"application/xml"、"application/xhtml+xml"、もしくは"image/svg+xml"(XMLパーサーを呼び出す)。

XMLパーサーの場合、文字列を解析できない場合、返されるDocumentは、結果のエラーを説明する要素が含まれる。

script 要素は解析中に評価されず、結果の文書のエンコーディングは常にUTF-8となることに注意する。文書のURLは、parserの関連するグローバルオブジェクトから継承される。

typeに上記以外の値を指定すると、TypeError例外が投げられる。

構築してからparseFromString()メソッドを呼び出す必要があるクラスとしてのDOMParserの設計は、不幸な歴史的成果物である。もし今日にこの機能を設計していたとしたら、それはスタンドアロン機能になっただろう。HTMLを解析する場合、現在の代替手段はDocument.parseHTMLUnsafe()である。

このメソッドは、scriptまたはイベントハンドラーコンテンツ属性のような潜在的に危険な要素および属性を削除するためのサニタイズを実行しない。

[Exposed=Window]
interface DOMParser {
  constructor();

  [NewObject] Document parseFromString((TrustedHTML or DOMString) string, DOMParserSupportedType type);
};

enum DOMParserSupportedType {
  "text/html",
  "text/xml",
  "application/xml",
  "application/xhtml+xml",
  "image/svg+xml"
};

The new DOMParser() constructor steps are to do nothing.

The parseFromString(string, type) method steps are:

  1. Let compliantString be the result of invoking the get trusted type compliant string algorithm with TrustedHTML, this's relevant global object, string, "DOMParser parseFromString", and "script".

  2. Let relevantDocument be this's relevant global object's associated Document.

  3. Let document be a new Document, whose content type is type, origin is relevantDocument's origin, and URL is relevantDocument's URL.

    The document's encoding will be left as its default, of UTF-8. In particular, any XML declarations or meta elements found while parsing compliantString will have no effect.

  4. Switch on type:

    "text/html"
    1. Parse HTML from a string given document and compliantString.

    Since document does not have a browsing context, scripting is disabled.

    Otherwise
    1. Create an XML parser parser, associated with document, and with XML scripting support disabled.

    2. Parse compliantString using parser.

    3. If the previous step resulted in an XML well-formedness or XML namespace well-formedness error:

      1. Assert: document has no child nodes.

      2. Let root be the result of creating an element given document, "parsererror", and "http://www.mozilla.org/newlayout/xml/parsererror.xml".

      3. Optionally, add attributes or children to root to describe the nature of the parsing error.

      4. Append root to document.

  5. Return document.

To parse HTML from a string, given a Document document, a string html, and an optional SanitizerConfig or null configuration (default null):

  1. Set document's type to "html".

  2. Let parser be a new HTML parser whose allow declarative shadow roots is document's allow declarative shadow roots and parser sanitizer configuration is configuration, associated with document.

  3. Place html into the input stream for parser. The encoding confidence is irrelevant.

  4. Start parser and let it run until it has consumed all the characters just inserted into the input stream.

    This might mutate the document's mode.

8.5.2 HTML解析および挿入メソッド

element.setHTML(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、その結果でelementの子(またはtemplate要素の場合はテンプレートコンテンツを置き換える。elementは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。elementがHTMLまたはSVGのscript要素である場合、何も行わない。

shadowRoot.setHTML(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、shadowRootの子をその結果に置き換える。shadowRootのhostは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。

element.appendHTML(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、その結果をelementの最後の子の後に挿入する(template要素の場合はテンプレートコンテンツの最後に挿入する)。elementは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。elementがhtml要素である場合、"HierarchyRequestError" DOMExceptionを投げる。elementがHTMLまたはSVGのscript要素である場合、何も行わない。

shadowRoot.appendHTML(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、 shadowRootの最後の子の後に結果を挿入する。shadowRootのhostは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。

element.prependHTML(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、その結果をelementの最初の子の前に挿入する(template要素の場合はテンプレートコンテンツの最後に挿入する)。elementは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。elementがhtml要素である場合、"HierarchyRequestError" DOMExceptionを投げる。elementがHTMLまたはSVGのscript要素である場合、何も行わない。

shadowRoot.prependHTML(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、 shadowRootの最初の子の前に結果を挿入する。shadowRootのhostは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。

node.beforeHTML(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、 nodeの前に結果を挿入する。nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。nodeの親がDocument、html要素、template要素、またはホストなしのDocumentFragmentである場合、"HierarchyRequestError" DOMExceptionを投げる。nodeが親を持たない、またはその親がHTMLもしくはSVGのscript要素である場合、何も行わない。

node.afterHTML(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、 nodeの後に結果を挿入する。nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。nodeの親がDocument、html要素、template要素、またはホストなしのDocumentFragmentである場合、"HierarchyRequestError" DOMExceptionを投げる。nodeが親を持たない、またはその親がHTMLもしくはSVGのscript要素である場合、何も行わない。

node.replaceWithHTML(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、nodeのその結果に置き換える。nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。nodeの親がDocument、html要素、template要素、またはホストなしのDocumentFragmentである場合、"HierarchyRequestError" DOMExceptionを投げる。nodeが親を持たない、またはその親がHTMLもしくはSVGのscript要素である場合、何も行わない。

element.setHTMLUnsafe(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、その結果でelementの子(またはtemplate要素の場合はテンプレートコンテンツを置き換える。elementは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。optionsのrunScriptsがtrueである場合、htmlに含まれるスクリプトは、ノードツリーが更新された直後に実行される(Trusted Typesのデフォルトポリシーによって変更されていない場合)。Trusted Typesが強制されており、かつoptionsがTrustedHTMLParserOptionsオブジェクトでない場合、デフォルトポリシーのcreateParserOptionsがnullまたはundefinedを返すとき、またはcreateParserOptionsを定義するデフォルトポリシーがなく、かつoptionsでrunScriptsが有効になる、または空でないsanitizerを指定する、もしくはhtmlがTrustedHTMLオブジェクトでないかのいずれかのとき(デフォルトポリシーのcreateHTMLがそのようなオブジェクトを返す場合を除く)、TypeErrorを投げる。デフォルトポリシーによって投げられた例外は再度投げられる。

shadowRoot.setHTMLUnsafe(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、shadowRootの子をその結果に置き換える。shadowRootのhostは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。optionsのrunScriptsがtrueである場合、htmlに含まれるスクリプトは、ノードツリーが更新された直後に実行される(Trusted Typesのデフォルトポリシーによって変更されていない場合)。Trusted Typesは、element.setHTMLUnsafe()と同じ方法で適用される。

element.appendHTMLUnsafe(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、その結果をelementの最後の子の後に挿入する(template要素の場合はテンプレートコンテンツの最後に挿入する)。elementは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。optionsのrunScriptsがtrueである場合、htmlに含まれるスクリプトは、ノードツリーが更新された直後に実行される(Trusted Typesのデフォルトポリシーによって変更されていない場合)。Trusted Typesは、elementのsetHTMLUnsafe()と同じ方法で適用される。elementがhtml要素である場合、"HierarchyRequestError" DOMExceptionを投げる。

shadowRoot.appendHTMLUnsafe(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、 shadowRootの最後の子の後に結果を挿入する。shadowRootのhostは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。optionsのrunScriptsがtrueである場合、htmlに含まれるスクリプトは、ノードツリーが更新された直後に実行される(Trusted Typesのデフォルトポリシーによって変更されていない場合)。Trusted Typesは、element.setHTMLUnsafe()と同じ方法で適用される。

element.prependHTMLUnsafe(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、その結果をelementの最初の子の前に挿入する(template要素の場合はテンプレートコンテンツの最後に挿入する)。elementは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。optionsのrunScriptsがtrueである場合、htmlに含まれるスクリプトは、ノードツリーが更新された直後に実行される(Trusted Typesのデフォルトポリシーによって変更されていない場合)。Trusted Typesは、elementのsetHTMLUnsafe()と同じ方法で適用される。elementがhtml要素である場合、"HierarchyRequestError" DOMExceptionを投げる。

shadowRoot.prependHTMLUnsafe(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、 shadowRootの最初の子の前に結果を挿入する。shadowRootのhostは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。optionsのrunScriptsがtrueである場合、htmlに含まれるスクリプトは、ノードツリーが更新された直後に実行される(Trusted Typesのデフォルトポリシーによって変更されていない場合)。Trusted Typesは、element.setHTMLUnsafe()と同じ方法で適用される。

node.beforeHTMLUnsafe(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、 nodeの前に結果を挿入する。nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。optionsのrunScriptsがtrueである場合、htmlに含まれるスクリプトは、ノードツリーが更新された直後に実行される(Trusted Typesのデフォルトポリシーによって変更されていない場合)。Trusted Typesは、element.setHTMLUnsafe()と同じ方法で適用される。nodeの親がDocument、html要素、template要素、またはホストなしのDocumentFragmentである場合、"HierarchyRequestError" DOMExceptionを投げる。nodeに親がない場合、何も起こらない。

node.afterHTMLUnsafe(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、 nodeの後に結果を挿入する。nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。optionsのrunScriptsがtrueである場合、htmlに含まれるスクリプトは、ノードツリーが更新された直後に実行される(Trusted Typesのデフォルトポリシーによって変更されていない場合)。Trusted Typesは、element.setHTMLUnsafe()と同じ方法で適用される。nodeの親がDocument、html要素、template要素、またはホストなしのDocumentFragmentである場合、"HierarchyRequestError" DOMExceptionを投げる。nodeに親がない場合、何も起こらない。

node.replaceWithHTMLUnsafe(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、nodeのその結果に置き換える。nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。optionsのrunScriptsがtrueである場合、htmlに含まれるスクリプトは、ノードツリーが更新された直後に実行される(Trusted Typesのデフォルトポリシーによって変更されていない場合)。Trusted Typesは、element.setHTMLUnsafe()と同じ方法で適用される。nodeの親がDocument、html要素、template要素、またはホストなしのDocumentFragmentである場合、"HierarchyRequestError" DOMExceptionを投げる。nodeに親がない場合、何も起こらない。

doc = Document.parseHTML(html, options)

指定されたoptionsでHTMLパーサーを使用してhtmlを解析し、その結果を含む新規Documentを返す。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。

doc = Document.parseHTMLUnsafe(html, options)

指定されたoptionsを使用してHTMLパーサーでhtmlを解析し、その結果のDocumentを返す。

script 要素は解析中に評価されず、結果の文書のエンコーディングは常にUTF-8となることに注意する。文書のURLは、about:blankになる。optionsがsanitizerメンバーを含むParseHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。Trusted Typesが強制されており、かつoptionsがTrustedHTMLParserOptionsオブジェクトでない場合、デフォルトポリシーのcreateParserOptionsがnullまたはundefinedを返すとき、またはcreateParserOptionsを定義するデフォルトポリシーがなく、かつoptionsで空でないsanitizerを指定する、またはhtmlがTrustedHTMLオブジェクトでないかのいずれかのとき(デフォルトポリシーのcreateHTMLがそのようなオブジェクトを返す場合を除く)、TypeErrorを投げる。デフォルトポリシーによって投げられた例外は再度投げられる。

デフォルトでは、Unsafe接尾辞を持つメソッドは、scriptまたはイベントハンドラーコンテンツ属性のような潜在的に危険な要素および属性を除去するためのサニタイズを一切行わない。

The HTML insertion methods are setHTML(), appendHTML(), prependHTML(), beforeHTML(), afterHTML(), and replaceWithHTML(), together with their Unsafe counterparts.

Element's setHTML(html, options) method steps are:

  1. Let target be the target for HTML insertion given this.

  2. Filter and set HTML given target, html, options, and Safe.

Element's appendHTML(html, options) method steps are:

  1. Let target be the target for HTML insertion given this.

  2. Filter and pre-insert HTML given target, null, html, options, and Safe.

Element's prependHTML(html, options) method steps are:

  1. Let target be the target for HTML insertion given this.

  2. Filter and pre-insert HTML given target, target's first child, html, options, and Safe.

ShadowRoot's setHTML(html, options) method steps are to filter and set HTML given this, html, options, and Safe.

ShadowRoot's appendHTML(html, options) method steps are to filter and pre-insert HTML given this, null, html, options, and Safe.

ShadowRoot's prependHTML(html, options) method steps are to filter and pre-insert HTML given this, this's first child, html, options, and Safe.

The NonDocumentTypeChildNode methods below are exposed on Element and CharacterData objects. Since mixin names are not observable, the Trusted Types sink names of their Unsafe counterparts use "Node" as the interface name (e.g., "Node beforeHTMLUnsafe").

NonDocumentTypeChildNode's beforeHTML(html, options) method steps are:

  1. Let parent be the parent for HTML insertion given this.

  2. If parent is null, then return.

  3. Filter and pre-insert HTML given parent, this, html, options, and Safe.

NonDocumentTypeChildNode's afterHTML(html, options) method steps are:

  1. Let parent be the parent for HTML insertion given this.

  2. If parent is null, then return.

  3. Filter and pre-insert HTML given parent, this's next sibling, html, options, and Safe.

NonDocumentTypeChildNode's replaceWithHTML(html, options) method steps are:

  1. Let parent be the parent for HTML insertion given this.

  2. If parent is null, then return.

  3. Filter and replace with HTML given parent, this, html, options, and Safe.

Element's setHTMLUnsafe(html, options) method steps are:

  1. Let (compliantHTML, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, html, options, and "Element setHTMLUnsafe".

  2. Let target be the target for HTML insertion given this.

  3. Filter and set HTML given target, compliantHTML, compliantOptions, and Unsafe.

Element's appendHTMLUnsafe(html, options) method steps are:

  1. Let (compliantHTML, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, html, options, and "Element appendHTMLUnsafe".

  2. Let target be the target for HTML insertion given this.

  3. Filter and pre-insert HTML given target, null, compliantHTML, compliantOptions, and Unsafe.

Element's prependHTMLUnsafe(html, options) method steps are:

  1. Let (compliantHTML, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, html, options, and "Element prependHTMLUnsafe".

  2. Let target be the target for HTML insertion given this.

  3. Filter and pre-insert HTML given target, target's first child, compliantHTML, compliantOptions, and Unsafe.

ShadowRoot's setHTMLUnsafe(html, options) method steps are:

  1. Let (compliantHTML, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, html, options, and "ShadowRoot setHTMLUnsafe".

  2. Filter and set HTML given this, compliantHTML, compliantOptions, and Unsafe.

ShadowRoot's appendHTMLUnsafe(html, options) method steps are:

  1. Let (compliantHTML, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, html, options, and "ShadowRoot appendHTMLUnsafe".

  2. Filter and pre-insert HTML given this, null, compliantHTML, compliantOptions, and Unsafe.

ShadowRoot's prependHTMLUnsafe(html, options) method steps are:

  1. Let (compliantHTML, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, html, options, and "ShadowRoot prependHTMLUnsafe".

  2. Filter and pre-insert HTML given this, this's first child, compliantHTML, compliantOptions, and Unsafe.

NonDocumentTypeChildNode's beforeHTMLUnsafe(html, options) method steps are:

  1. Let (compliantHTML, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, html, options, and "Node beforeHTMLUnsafe".

  2. Let parent be the parent for HTML insertion given this.

  3. If parent is null, then return.

  4. Filter and pre-insert HTML given parent, this, compliantHTML, compliantOptions, and Unsafe.

NonDocumentTypeChildNode's afterHTMLUnsafe(html, options) method steps are:

  1. Let (compliantHTML, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, html, options, and "Node afterHTMLUnsafe".

  2. Let parent be the parent for HTML insertion given this.

  3. If parent is null, then return.

  4. Filter and pre-insert HTML given parent, this's next sibling, compliantHTML, compliantOptions, and Unsafe.

NonDocumentTypeChildNode's replaceWithHTMLUnsafe(html, options) method steps are:

  1. Let (compliantHTML, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, html, options, and "Node replaceWithHTMLUnsafe".

  2. Let parent be the parent for HTML insertion given this.

  3. If parent is null, then return.

  4. Filter and replace with HTML given parent, this, compliantHTML, compliantOptions, and Unsafe.


The static parseHTML(html, options) method steps are:

  1. Let document be a new Document, whose content type is "text/html" and origin is this's relevant global object's associated Document's origin.

    Since document does not have a browsing context, scripting is disabled.

  2. Set document's allow declarative shadow roots to true.

  3. Let sanitizerConfig be the result of getting a sanitizer config from options given options and true.

  4. Assert: sanitizerConfig is non-null.

    The sanitizer member of SetHTMLOptions defaults to "default".

  5. Parse HTML from a string given document, html, and sanitizerConfig.

  6. Return document.

The static parseHTMLUnsafe(html, options) method steps are:

  1. Let (compliantHTML, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with the current global object, html, options, and "Document parseHTMLUnsafe".

  2. Let document be a new Document, whose content type is "text/html" and origin is this's relevant global object's associated Document's origin.

    Since document does not have a browsing context, scripting is disabled.

  3. Set document's allow declarative shadow roots to true.

  4. Let sanitizerConfig be the result of getting a sanitizer config from options given compliantOptions and false.

  5. Parse HTML from a string given document, compliantHTML, and sanitizerConfig.

  6. Return document.

8.5.3 HTML streaming methods

stream = element.streamHTML([options])

Removes element's children (or the template contents's children in the case of a template element), and returns a WritableStream that, as strings are written to it, parses them using the HTML parser and incrementally inserts the result. elementは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。Throws a "NotSupportedError" DOMException if element is an HTML or SVG script element.

stream = shadowRoot.streamHTML([options])

Removes shadowRoot's children, and returns a WritableStream that, as strings are written to it, parses them using the HTML parser and incrementally inserts the result. shadowRootのhostは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。

stream = element.streamAppendHTML([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result after the last child of element (or of the template contents in the case of a template element). elementは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。elementがhtml要素である場合、"HierarchyRequestError" DOMExceptionを投げる。Throws a "NotSupportedError" DOMException if element is an HTML or SVG script element.

stream = shadowRoot.streamAppendHTML([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result after the last child of shadowRoot. shadowRootのhostは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。

stream = element.streamPrependHTML([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result before the first child of element (or of the template contents in the case of a template element). elementは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。elementがhtml要素である場合、"HierarchyRequestError" DOMExceptionを投げる。Throws a "NotSupportedError" DOMException if element is an HTML or SVG script element. While streaming, content is inserted before the node that was element's first child (or the template contents's first child) when the method was called. The stream errors with a "HierarchyRequestError" DOMException if that node is no longer a child of element (or of the template contents). If there is no such child when the method is called, streamed content is appended, so children added later by other means end up before it.

stream = shadowRoot.streamPrependHTML([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result before the first child of shadowRoot. shadowRootのhostは、HTMLパーサーのコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。While streaming, content is inserted before the node that was shadowRoot's first child when the method was called. The stream errors with a "HierarchyRequestError" DOMException if that node is no longer a child of shadowRoot. If there is no such child when the method is called, streamed content is appended, so children added later by other means end up before it.

stream = node.streamBeforeHTML([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result before node. nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。Throws a "HierarchyRequestError" DOMException if node's parent is null, a Document, an html element, a template element, or a DocumentFragment without a host. Throws a "NotSupportedError" DOMException if node's parent is an HTML or SVG script element. The stream errors with a "HierarchyRequestError" DOMException if node is no longer a child of its original parent.

stream = node.streamAfterHTML([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result after node. nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。Throws a "HierarchyRequestError" DOMException if node's parent is null, a Document, an html element, a template element, or a DocumentFragment without a host. Throws a "NotSupportedError" DOMException if node's parent is an HTML or SVG script element. While streaming, content is inserted before the node that was node's next sibling when the method was called (or after the last child of node's original parent if it was the last child). The stream errors with a "HierarchyRequestError" DOMException if that next sibling is no longer a child of node's original parent.

stream = node.streamReplaceWithHTML([options])

Removes node, and returns a WritableStream that, as strings are written to it, parses them using the HTML parser and incrementally inserts the result in its place. nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。マークアップは、解析時にoptionsのsanitizerメンバーに基づいてサニタイズされ、安全でないコンテンツは除去される。Throws a "HierarchyRequestError" DOMException if node's parent is null, a Document, an html element, a template element, or a DocumentFragment without a host. Throws a "NotSupportedError" DOMException if node's parent is an HTML or SVG script element. While streaming, content is inserted before the node that was node's next sibling when the method was called (or after the last child of node's former parent if it was the last child). The stream errors with a "HierarchyRequestError" DOMException if that next sibling is no longer a child of node's former parent.

stream = element.streamHTMLUnsafe([options])

Removes element's children (or the template contents's children in the case of a template element), and returns a WritableStream that, as strings are written to it, parses them using the HTML parser and incrementally inserts the result. elementは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。If options's runScripts is true, scripts written to the stream that are connected (and in the same document) when parsed will be executed as they are parsed (or once fetched for async scripts, or when the stream closes for external defer scripts and non-async "module" scripts), unless altered by a Trusted Types default policy. Throws a "NotSupportedError" DOMException if element is an HTML or SVG script element. If Trusted Types are enforced and options is not a TrustedHTMLParserOptions object, throws a TypeError if no default policy defines createParserOptions or a default policy's createParserOptions returns null or undefined. Exceptions thrown by createParserOptions are rethrown.

stream = shadowRoot.streamHTMLUnsafe([options])

Removes shadowRoot's children, and returns a WritableStream that, as strings are written to it, parses them using the HTML parser and incrementally inserts the result. shadowRootのhostは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。If options's runScripts is true, scripts written to the stream that are connected (and in the same document) when parsed will be executed as they are parsed (or once fetched for async scripts, or when the stream closes for external defer scripts and non-async "module" scripts), unless altered by a Trusted Types default policy. Trusted Types are enforced in the same way as for element.streamHTMLUnsafe().

stream = element.streamAppendHTMLUnsafe([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result after the last child of element (or of the template contents in the case of a template element). elementは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。If options's runScripts is true, scripts written to the stream that are connected (and in the same document) when parsed will be executed as they are parsed (or once fetched for async scripts, or when the stream closes for external defer scripts and non-async "module" scripts), unless altered by a Trusted Types default policy. Throws a "HierarchyRequestError" DOMException if element is an html element. Throws a "NotSupportedError" DOMException if element is an HTML or SVG script element. Trusted Types are enforced in the same way as for element.streamHTMLUnsafe().

stream = shadowRoot.streamAppendHTMLUnsafe([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result after the last child of shadowRoot. shadowRootのhostは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。If options's runScripts is true, scripts written to the stream that are connected (and in the same document) when parsed will be executed as they are parsed (or once fetched for async scripts, or when the stream closes for external defer scripts and non-async "module" scripts), unless altered by a Trusted Types default policy. Trusted Types are enforced in the same way as for element.streamHTMLUnsafe().

stream = element.streamPrependHTMLUnsafe([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result before the first child of element (or of the template contents in the case of a template element). elementは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。If options's runScripts is true, scripts written to the stream that are connected (and in the same document) when parsed will be executed as they are parsed (or once fetched for async scripts, or when the stream closes for external defer scripts and non-async "module" scripts), unless altered by a Trusted Types default policy. Throws a "HierarchyRequestError" DOMException if element is an html element. Throws a "NotSupportedError" DOMException if element is an HTML or SVG script element. Trusted Types are enforced in the same way as for element.streamHTMLUnsafe(). While streaming, content is inserted before the node that was element's first child (or the template contents's first child) when the method was called. The stream errors with a "HierarchyRequestError" DOMException if that node is no longer a child of element (or of the template contents). If there is no such child when the method is called, streamed content is appended, so children added later by other means end up before it.

stream = shadowRoot.streamPrependHTMLUnsafe([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result before the first child of shadowRoot. shadowRootのhostは、HTMLパーサーのコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。If options's runScripts is true, scripts written to the stream that are connected (and in the same document) when parsed will be executed as they are parsed (or once fetched for async scripts, or when the stream closes for external defer scripts and non-async "module" scripts), unless altered by a Trusted Types default policy. Trusted Types are enforced in the same way as for element.streamHTMLUnsafe(). While streaming, content is inserted before the node that was shadowRoot's first child when the method was called. The stream errors with a "HierarchyRequestError" DOMException if that node is no longer a child of shadowRoot. If there is no such child when the method is called, streamed content is appended, so children added later by other means end up before it.

stream = node.streamBeforeHTMLUnsafe([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result before node. nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。If options's runScripts is true, scripts written to the stream that are connected (and in the same document) when parsed will be executed as they are parsed (or once fetched for async scripts, or when the stream closes for external defer scripts and non-async "module" scripts), unless altered by a Trusted Types default policy. Throws a "HierarchyRequestError" DOMException if node's parent is null, a Document, an html element, a template element, or a DocumentFragment without a host. Throws a "NotSupportedError" DOMException if node's parent is an HTML or SVG script element. Trusted Types are enforced in the same way as for element.streamHTMLUnsafe(). The stream errors with a "HierarchyRequestError" DOMException if node is no longer a child of its original parent.

stream = node.streamAfterHTMLUnsafe([options])

Returns a WritableStream that, as strings are written to it, parses them using the HTML parser, and incrementally inserts the result after node. nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。If options's runScripts is true, scripts written to the stream that are connected (and in the same document) when parsed will be executed as they are parsed (or once fetched for async scripts, or when the stream closes for external defer scripts and non-async "module" scripts), unless altered by a Trusted Types default policy. Throws a "HierarchyRequestError" DOMException if node's parent is null, a Document, an html element, a template element, or a DocumentFragment without a host. Throws a "NotSupportedError" DOMException if node's parent is an HTML or SVG script element. Trusted Types are enforced in the same way as for element.streamHTMLUnsafe(). While streaming, content is inserted before the node that was node's next sibling when the method was called (or after the last child of node's original parent if it was the last child). The stream errors with a "HierarchyRequestError" DOMException if that next sibling is no longer a child of node's original parent.

stream = node.streamReplaceWithHTMLUnsafe([options])

Removes node, and returns a WritableStream that, as strings are written to it, parses them using the HTML parser and incrementally inserts the result in its place. nodeの親(または、その親が シャドウルートまたはテンプレートコンテンツである場合、その親のホスト)は、HTMLパーサーにコンテキストを提供する。optionsがsanitizerメンバーを含むSetHTMLUnsafeOptionsディクショナリー、または非nullのサニタイザー設定をもつTrustedHTMLParserOptionsオブジェクトである場合、これはマークアップが解析されるときにマークアップをサニタイズするために使用される。If options's runScripts is true, scripts written to the stream that are connected (and in the same document) when parsed will be executed as they are parsed (or once fetched for async scripts, or when the stream closes for external defer scripts and non-async "module" scripts), unless altered by a Trusted Types default policy. Throws a "HierarchyRequestError" DOMException if node's parent is null, a Document, an html element, a template element, or a DocumentFragment without a host. Throws a "NotSupportedError" DOMException if node's parent is an HTML or SVG script element. Trusted Types are enforced in the same way as for element.streamHTMLUnsafe(). While streaming, content is inserted before the node that was node's next sibling when the method was called (or after the last child of node's former parent if it was the last child). The stream errors with a "HierarchyRequestError" DOMException if that next sibling is no longer a child of node's former parent.

Chunks written to the stream are converted to strings; to stream bytes (such as from a Response body), pipe them through a TextDecoderStream first. Writing a chunk settles without waiting for parser-blocking script fetches, whereas closing the stream waits until all input has been parsed and parser-blocking scripts have executed. When runScripts is true, streamed scripts run in the live document rather than the stream's parser (so document.write() targets the live document) and are not blocked by style sheets.

デフォルトでは、Unsafe接尾辞を持つメソッドは、scriptまたはイベントハンドラーコンテンツ属性のような潜在的に危険な要素および属性を除去するためのサニタイズを一切行わない。

The HTML streaming methods are streamHTML(), streamAppendHTML(), streamPrependHTML(), streamBeforeHTML(), streamAfterHTML(), and streamReplaceWithHTML(), together with their Unsafe counterparts.

Element's streamHTML(options) method steps are:

  1. Let target be the target for HTML insertion given this.

  2. Let stream be the result of running stream HTML given target, null, options, Safe, and this's relevant realm.

  3. Replace all with null within target.

  4. Return stream.

Element's streamAppendHTML(options) method steps are:

  1. Let target be the target for HTML insertion given this.

  2. If target is an html element, then throw a "HierarchyRequestError" DOMException.

  3. Return the result of running stream HTML given target, null, options, Safe, and this's relevant realm.

Element's streamPrependHTML(options) method steps are:

  1. Let target be the target for HTML insertion given this.

  2. If target is an html element, then throw a "HierarchyRequestError" DOMException.

  3. Return the result of running stream HTML given target, target's first child, options, Safe, and this's relevant realm.

Element's streamHTMLUnsafe(options) method steps are:

  1. Let compliantOptions be the result of invoking the get trusted type compliant parser options algorithm with this's relevant global object, options, true, and "Element streamHTMLUnsafe".

  2. Let target be the target for HTML insertion given this.

  3. Let stream be the result of running stream HTML given target, null, compliantOptions, Unsafe, and this's relevant realm.

  4. Replace all with null within target.

  5. Return stream.

Element's streamAppendHTMLUnsafe(options) method steps are:

  1. Let compliantOptions be the result of invoking the get trusted type compliant parser options algorithm with this's relevant global object, options, true, and "Element streamAppendHTMLUnsafe".

  2. Let target be the target for HTML insertion given this.

  3. If target is an html element, then throw a "HierarchyRequestError" DOMException.

  4. Return the result of running stream HTML given target, null, compliantOptions, Unsafe, and this's relevant realm.

Element's streamPrependHTMLUnsafe(options) method steps are:

  1. Let compliantOptions be the result of invoking the get trusted type compliant parser options algorithm with this's relevant global object, options, true, and "Element streamPrependHTMLUnsafe".

  2. Let target be the target for HTML insertion given this.

  3. If target is an html element, then throw a "HierarchyRequestError" DOMException.

  4. Return the result of running stream HTML given target, target's first child, compliantOptions, Unsafe, and this's relevant realm.

ShadowRoot's streamHTML(options) method steps are:

  1. Let stream be the result of running stream HTML given this, null, options, Safe, and this's relevant realm.

  2. Replace all with null within this.

  3. Return stream.

ShadowRoot's streamAppendHTML(options) method steps are to return the result of running stream HTML given this, null, options, Safe, and this's relevant realm.

ShadowRoot's streamPrependHTML(options) method steps are to return the result of running stream HTML given this, this's first child, options, Safe, and this's relevant realm.

ShadowRoot's streamHTMLUnsafe(options) method steps are:

  1. Let compliantOptions be the result of invoking the get trusted type compliant parser options algorithm with this's relevant global object, options, true, and "ShadowRoot streamHTMLUnsafe".

  2. Let stream be the result of running stream HTML given this, null, compliantOptions, Unsafe, and this's relevant realm.

  3. Replace all with null within this.

  4. Return stream.

ShadowRoot's streamAppendHTMLUnsafe(options) method steps are:

  1. Let compliantOptions be the result of invoking the get trusted type compliant parser options algorithm with this's relevant global object, options, true, and "ShadowRoot streamAppendHTMLUnsafe".

  2. Return the result of running stream HTML given this, null, compliantOptions, Unsafe, and this's relevant realm.

ShadowRoot's streamPrependHTMLUnsafe(options) method steps are:

  1. Let compliantOptions be the result of invoking the get trusted type compliant parser options algorithm with this's relevant global object, options, true, and "ShadowRoot streamPrependHTMLUnsafe".

  2. Return the result of running stream HTML given this, this's first child, compliantOptions, Unsafe, and this's relevant realm.

NonDocumentTypeChildNode's streamBeforeHTML(options) method steps are:

  1. Let parent be the parent for HTML streaming given this.

  2. Return the result of running stream HTML given parent, this, options, Safe, and this's relevant realm.

NonDocumentTypeChildNode's streamAfterHTML(options) method steps are:

  1. Let parent be the parent for HTML streaming given this.

  2. Return the result of running stream HTML given parent, this's next sibling, options, Safe, and this's relevant realm.

NonDocumentTypeChildNode's streamReplaceWithHTML(options) method steps are:

  1. Let parent be the parent for HTML streaming given this.

  2. Let stream be the result of running stream HTML given parent, this's next sibling, options, Safe, and this's relevant realm.

  3. Remove this.

  4. Return stream.

NonDocumentTypeChildNode's streamBeforeHTMLUnsafe(options) method steps are:

  1. Let compliantOptions be the result of invoking the get trusted type compliant parser options algorithm with this's relevant global object, options, true, and "Node streamBeforeHTMLUnsafe".

  2. Let parent be the parent for HTML streaming given this.

  3. Return the result of running stream HTML given parent, this, compliantOptions, Unsafe, and this's relevant realm.

NonDocumentTypeChildNode's streamAfterHTMLUnsafe(options) method steps are:

  1. Let compliantOptions be the result of invoking the get trusted type compliant parser options algorithm with this's relevant global object, options, true, and "Node streamAfterHTMLUnsafe".

  2. Let parent be the parent for HTML streaming given this.

  3. Return the result of running stream HTML given parent, this's next sibling, compliantOptions, Unsafe, and this's relevant realm.

NonDocumentTypeChildNode's streamReplaceWithHTMLUnsafe(options) method steps are:

  1. Let compliantOptions be the result of invoking the get trusted type compliant parser options algorithm with this's relevant global object, options, true, and "Node streamReplaceWithHTMLUnsafe".

  2. Let parent be the parent for HTML streaming given this.

  3. Let stream be the result of running stream HTML given parent, this's next sibling, compliantOptions, Unsafe, and this's relevant realm.

  4. Remove this.

  5. Return stream.

To get the parent for HTML streaming given a Node node:

  1. Let parent be the parent for HTML insertion given node.

  2. If parent is null or an html element, then throw a "HierarchyRequestError" DOMException.

  3. Return parent.

To stream HTML given an Element or DocumentFragment target, a Node or null referenceChild, a SetHTMLOptions or SetHTMLUnsafeOptions dictionary or a TrustedHTMLParserOptions object options, a fragment parser mode mode, and a realm realm:

  1. Let context be the parser context element given target.

  2. If context's local name is "script" and context's namespace is the HTML namespace or the SVG namespace, then throw a "NotSupportedError" DOMException.

  3. Let safe be true if mode is Safe; otherwise false.

  4. Let sanitizerConfig be the result of getting a sanitizer config from options given options and safe.

  5. Let runScripts be options's runScripts if options is a TrustedHTMLParserOptions; otherwise options["runScripts"] with default false.

  6. Assert: runScripts is false or mode is not Safe.

  7. Let document be a Document node whose type is "html".

  8. Let parser be the result of initializing an HTML fragment parser given document, target, (target, referenceChild), true, runScripts, and sanitizerConfig. parser is a script-created parser.

    As a script-created parser, parser only reaches the end of its input stream when the explicit "EOF" character is appended upon closing the stream. Because style sheets are inserted into target's node document rather than document, document never has a style sheet that is blocking scripts.

  9. Let stream be a new WritableStream created in realm.

  10. Let writeError be null.

  11. If referenceChild is non-null, then set parser's invalid reference child steps to the following steps given a Node child:

    1. If child is not referenceChild, or referenceChild's parent is target, then return.

    2. Set parser's invalid reference child steps to null.

    3. Let error be a new "HierarchyRequestError" DOMException created in realm.

    4. Set writeError to error.

    5. Error stream with error.

    6. If parser's fragment parser close promise is non-null, then reject parser's fragment parser close promise with error and set parser's fragment parser close promise to null.

    7. Abort parser.

  12. Let writeAlgorithm be the following steps given chunk:

    1. Let chunkString be the result of converting chunk to a DOMString. If this throws an exception e, catch it, abort parser, and return a promise rejected with e in realm.

    2. If referenceChild is non-null, referenceChild's parent is not target, and parser's invalid reference child steps are non-null, then run parser's invalid reference child steps given referenceChild.

      This catches referenceChild being moved or removed before parser runs or when a chunk produces no nodes to insert before it; mutations during parsing are caught in adjusted insertion location.

    3. If writeError is non-null, then return a promise rejected with writeError in realm.

    4. Append chunkString to the end of parser's input stream, and run a fragment parser given parser. The encoding confidence is irrelevant.

    5. If writeError is non-null, then return a promise rejected with writeError in realm.

    6. Return a promise resolved with undefined in realm.

      The returned promise does not wait for any pending parsing-blocking script, and resolves before chunkString is parsed if parser's fragment parser running is true.

  13. Let closeAlgorithm be the following steps:

    1. Let closePromise be a new promise created in realm.

    2. Set parser's fragment parser close promise to closePromise.

    3. Append an explicit "EOF" character to the end of parser's input stream, and run a fragment parser given parser.

    4. Return closePromise.

      closePromise settles once parser stops parsing (before any deferred scripts execute), or rejects if stream errors while closing.

  14. Let abortAlgorithm be the following steps given reason:

    1. Abort parser.

    2. Return a promise resolved with undefined in realm.

  15. Set up stream with writeAlgorithm set to writeAlgorithm, closeAlgorithm set to closeAlgorithm, and abortAlgorithm set to abortAlgorithm.

  16. Return stream.

8.5.4 HTML serialization methods

html = element.getHTML({ serializableShadowRoots, shadowRoots })

elementをHTMLにシリアル化した結果を返す。element内のシャドウルートは、指定されたオプションに従ってシリアル化される。

どちらのオプションも指定しない場合、シャドウルートはシリアル化されない。

html = shadowRoot.getHTML({ serializableShadowRoots, shadowRoots })

コンテキスト要素としてシャドウホストを使用して、shadowRootをHTMLにシリアル化した結果を返す。shadowRoot内のシャドウルートは、上記のように、指定されたオプションに従ってシリアル化される。

Element's getHTML(options) method steps are to return the result of HTML fragment serialization algorithm with this, options["serializableShadowRoots"], and options["shadowRoots"].

ShadowRoot's getHTML(options) method steps are to return the result of HTML fragment serialization algorithm with this, options["serializableShadowRoots"], and options["shadowRoots"].

8.5.5 The innerHTML property

innerHTMLプロパティには、DOM Parsing and Serialization issue trackerに未解決の問題が多数あり、その仕様に関するさまざまな問題が文書化されている。

element.innerHTML

要素の内容を表すHTMLまたはXMLのフラグメントを返す。

XML文書の場合、要素をXMLにシリアル化できない場合、"InvalidStateError" DOMExceptionを投げる。

element.innerHTML = value

要素の内容を、指定された文字列から解析されたノードに置き換える。

XML文書の場合、指定した文字列が整形式でない場合、"SyntaxError" DOMExceptionを投げる。

template要素にinnerHTMLを設定すると、その子供ではなく、テンプレートコンテンツ内のすべてのノードが置き換えられる。

shadowRoot.innerHTML

シャドウルートの内容を表すHTMLのフラグメントを返す。

shadowRoot.innerHTML = value

シャドウルートの内容を、指定した文字列から解析されたノードに置き換える。

デフォルトでは、これらのプロパティのsetterは、scriptやイベントハンドラーコンテンツ属性などの潜在的に危険な要素および属性を除去するためのサニタイズを実行しない。

The fragment serializing algorithm steps, given an Element, Document, or DocumentFragment node and a boolean require well-formed, are:

  1. Let context document be node's node document.

  2. If context document is an HTML document, then return the result of HTML fragment serialization algorithm with node, false, and « ».

  3. Return the XML serialization of node given require well-formed.

A fragment parser mode is one of the following:

Safe

Unsafe elements and attributes are removed, and allow declarative shadow roots is true. The HTML parser is used regardless of the type of document.

安全でない

Unsafe elements and attributes are not removed unless a sanitizer is supplied, and allow declarative shadow roots is true. The HTML parser is used regardless of the type of document.

Legacy

Unsafe elements and attributes are not removed unless a sanitizer is supplied, and allow declarative shadow roots is false. In XML documents, the XML parser is used.

To get the target for HTML insertion, given an Element element:

  1. If element is a template element, then return element's template contents.

  2. Return element.

To get the parent for HTML insertion, given a Node node:

  1. Let parent be node's parent.

  2. If parent is null, then return null.

  3. If parent is a template element, then throw a "HierarchyRequestError" DOMException.

  4. If parent is an Element, or a DocumentFragment with a non-null host, then return parent.

  5. Throw a "HierarchyRequestError" DOMException.

This diverges from the DOM insertion methods (such as before()), which only reject such insertions when the resulting tree would be invalid, and from insertAdjacentHTML(), which allows inserting adjacent to a child of a template element or inside an html element. The HTML insertion methods and HTML streaming methods require an Element context for the fragment parser, which a Document or hostless DocumentFragment cannot provide, and they treat a template element as standing for its template contents rather than its children, so inserting adjacent to the latter is disallowed. Similarly, except when replacing all children (via setHTML(), streamHTML(), or their Unsafe counterparts), they disallow an html element as the target or parent, because parsing a fragment with an html context element always produces both a head and a body element. Additionally, while legacy methods such as outerHTML and insertAdjacentHTML() throw a "NoModificationAllowedError" DOMException when the parent is a Document, the HTML insertion methods and HTML streaming methods throw a "HierarchyRequestError" DOMException instead.

To filter and set HTML, given an Element or DocumentFragment target, a string html, a SetHTMLOptions or SetHTMLUnsafeOptions dictionary, or a TrustedHTMLParserOptions object options, and a fragment parser mode mode:

  1. Let fragment be the result of parsing HTML for insertion given target, html, options, and mode.

  2. If fragment is non-null, then replace all with fragment within target.

To filter and pre-insert HTML, given an Element or DocumentFragment parent, a Node-or-null child, a string html, a SetHTMLOptions or SetHTMLUnsafeOptions dictionary, or a TrustedHTMLParserOptions object options, and a fragment parser mode mode:

  1. If parent is an html element, then throw a "HierarchyRequestError" DOMException.

  2. Let fragment be the result of parsing HTML for insertion given parent, html, options, and mode.

  3. If fragment is non-null, then pre-insert fragment into parent before child.

To filter and replace with HTML, given an Element or DocumentFragment parent, a Node node, a string html, a SetHTMLOptions or SetHTMLUnsafeOptions dictionary, or a TrustedHTMLParserOptions object options, and a fragment parser mode mode:

  1. If parent is an html element, then throw a "HierarchyRequestError" DOMException.

  2. Let fragment be the result of parsing HTML for insertion given parent, html, options, and mode.

  3. If fragment is non-null, then replace node with fragment within parent.

To parse HTML for insertion, given an Element or DocumentFragment target, a string html, a SetHTMLOptions or SetHTMLUnsafeOptions dictionary, or a TrustedHTMLParserOptions object options, and a fragment parser mode mode:

  1. If mode is Safe:

    1. Let context be the parser context element given target.

    2. If all of the following are true:

      then return null.

  2. Return the result of invoking the fragment parsing algorithm steps given target, html, options, and mode.

The fragment parsing algorithm steps, given an Element or DocumentFragment target, a string markup, a SetHTMLOptions or SetHTMLUnsafeOptions dictionary, or a TrustedHTMLParserOptions object options, and a fragment parser mode mode, are:

  1. If mode is Legacy and target's node document is an XML document, then return the result of invoking the XML fragment parsing algorithm given target and markup.

    Sanitization is not supported for XML documents.

  2. Let safe be true if mode is Safe; otherwise false.

  3. Let sanitizerConfig be the result of getting a sanitizer config from options given options and safe.

  4. Let runScripts be options's runScripts if options is a TrustedHTMLParserOptions; otherwise options["runScripts"] with default false.

  5. Assert: runScripts is false or mode is not Safe.

  6. Let allowDeclarativeShadowRoots be false if mode is Legacy; otherwise true.

  7. Return the result of invoking the HTML fragment parsing algorithm given target, markup, allowDeclarativeShadowRoots, runScripts, and sanitizerConfig.

    Scripts in the returned fragment will only execute once they are inserted into a document, and only if runScripts is true.

Element's innerHTML getter steps are to return the result of running fragment serializing algorithm steps with this and true.

ShadowRoot's innerHTML getter steps are to return the result of running fragment serializing algorithm steps with this and true.

Element's innerHTML setter steps are:

  1. Let (compliantString, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, the given value, a new SetHTMLUnsafeOptions dictionary, "Element innerHTML", this's node document's type, and false.

  2. Let target be the target for HTML insertion given this.

  3. Filter and set HTML given target, compliantString, compliantOptions, and Legacy.

ShadowRoot's innerHTML setter steps are:

  1. Let (compliantString, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, the given value, a new SetHTMLUnsafeOptions dictionary, "ShadowRoot innerHTML", this's node document's type, and false.

  2. Filter and set HTML given this, compliantString, compliantOptions, and Legacy.

8.5.6 The outerHTML property

outerHTMLプロパティには、DOM Parsing and Serialization issue trackerに未解決の問題が多数あり、その仕様に関するさまざまな問題が文書化されている。

element.outerHTML

要素とその内容を表すHTMLまたはXMLのフラグメントを返す。

XML文書の場合、要素をXMLにシリアル化できない場合、"InvalidStateError" DOMExceptionを投げる。

element.outerHTML = value

要素を、指定された文字列から解析されたノードに置き換える。

XML文書の場合、指定した文字列が整形式でない場合、"SyntaxError" DOMExceptionを投げる。

要素の親がDocumentである場合、"NoModificationAllowedError" DOMExceptionを返す。

デフォルトでは、このプロパティのsetterは、scriptやイベントハンドラーコンテンツ属性などの潜在的に危険な要素および属性を除去するためのサニタイズを実行しない。

Element's outerHTML getter steps are:

  1. Let element be a fictional node whose only child is this.

  2. Return the result of running fragment serializing algorithm steps with element and true.

Element's outerHTML setter steps are:

  1. Let (compliantString, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, the given value, a new SetHTMLUnsafeOptions dictionary, "Element outerHTML", this's node document's type, and false.

  2. Let parent be this's parent.

  3. If parent is null, return. There would be no way to obtain a reference to the nodes created even if the remaining steps were run.

  4. If parent is a Document, throw a "NoModificationAllowedError" DOMException.

  5. If parent is a DocumentFragment, set parent to the result of creating an element given this's node document, "body", and the HTML namespace.

  6. Let fragment be the result of invoking the fragment parsing algorithm steps given parent, compliantString, compliantOptions, and Legacy.

  7. Replace this with fragment within this's parent.

8.5.7 The insertAdjacentHTML() method

insertAdjacentHTML()メソッドには、DOM Parsing and Serialization issue trackerに未解決の問題が多数あり、その仕様に関するさまざまな問題が文書化されている。

element.insertAdjacentHTML(position, string)

stringをHTMLまたはXMLとして解析し、結果のノードを次のようにposition引数で指定された位置にツリーに挿入する:

"beforebegin"
要素自体の前(つまり、elementの前の兄弟の後)
"afterbegin"
要素のすぐ内側で、最初の子の前。
"beforeend"
要素の内部で、最後の子の後。
"afterend"
要素自体の前(つまり、elementの次の兄弟の前)

引数に無効な値が含まれている場合に"SyntaxError" DOMExceptionを投げる(たとえば、XML文書の場合、指定された文字列が整形式でない場合)。

指定した位置が使用できない場合に"NoModificationAllowedError" DOMExceptionを投げる(たとえば、Documentのルート要素の後に要素を挿入する場合など)。

デフォルトでは、このメソッドは、scriptやイベントハンドラーコンテンツ属性のような潜在的に危険な要素および属性を除去するためのサニタイズを実行しない。

Element's insertAdjacentHTML(position, string) method steps are:

  1. Let (compliantString, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, string, a new SetHTMLUnsafeOptions dictionary, "Element insertAdjacentHTML", this's node document's type, and false.

  2. Let context be null.

  3. Use the first matching item from this list:

    If position is an ASCII case-insensitive match for the string "beforebegin"
    If position is an ASCII case-insensitive match for the string "afterend"
    1. Set context to this's parent.

    2. If context is null or a Document, throw a "NoModificationAllowedError" DOMException.

    If position is an ASCII case-insensitive match for the string "afterbegin"
    If position is an ASCII case-insensitive match for the string "beforeend"
    Set context to this.
    そうでなければ

    Throw a "SyntaxError" DOMException.

  4. If context is not an Element or all of the following are true:

    then set context to the result of creating an element given this's node document, "body", and the HTML namespace.

  5. Let fragment be the result of invoking the fragment parsing algorithm steps given context, compliantString, compliantOptions, and Legacy.

  6. Use the first matching item from this list:
    If position is an ASCII case-insensitive match for the string "beforebegin"

    Insert fragment into this's parent before this.

    If position is an ASCII case-insensitive match for the string "afterbegin"

    Insert fragment into this before its first child.

    If position is an ASCII case-insensitive match for the string "beforeend"

    Append fragment to this.

    If position is an ASCII case-insensitive match for the string "afterend"

    Insert fragment into this's parent before this's next sibling.

As with other direct Node-manipulation APIs (and unlike innerHTML), insertAdjacentHTML() does not include any special handling for template elements. In most cases you will want to use templateEl.content.insertAdjacentHTML() instead of directly manipulating the child nodes of a template element.

8.5.8 The createContextualFragment() method

createContextualFragment()メソッドには、DOM Parsing and Serialization issue trackerに未解決の問題が多数あり、その仕様に関するさまざまな問題が文書化されている。

docFragment = range.createContextualFragment(string)

fragmentが解析されるコンテキストとしてrangeの開始ノードを使用して、マークアップ文字列stringから作成された DocumentFragmentを返す。

デフォルトでは、このメソッドは、scriptやイベントハンドラーコンテンツ属性のような潜在的に危険な要素および属性を除去するためのサニタイズを実行しない。

partial interface Range {
  [CEReactions, NewObject] DocumentFragment createContextualFragment((TrustedHTML or DOMString) string);
};

Range's createContextualFragment(string) method steps are:

  1. Let node be this's start node.

  2. Let (compliantString, compliantOptions) be the result of invoking the get trusted type compliant input algorithm with this's relevant global object, string, a new SetHTMLUnsafeOptions dictionary whose runScripts member is set to true and whose other members are set to their default values, "Range createContextualFragment", node's node document's type, and false.

    A Trusted Types default policy can override the options, for example by setting runScripts to false to prevent scripts from executing when inserting the returned fragment.

  3. Let element be null.

  4. If node implements Element, set element to node.

  5. Otherwise, if node implements Text or Comment, set element to node's parent element.

  6. If element is null or all of the following are true:

    then set element to the result of creating an element given node's node document, "body", and the HTML namespace.

  7. Return the result of invoking the fragment parsing algorithm steps given element, compliantString, compliantOptions, and Legacy.

8.5.9 The XMLSerializer interface

XMLSerializeインターフェイスには、DOM Parsing and Serialization issue trackerに未解決の問題が多数あり、その仕様に関するさまざまな問題が文書化されている。DOM Parsing and Serializationの残りの部分は、この仕様に徐々にアップストリームされまる。

xmlSerializer = new XMLSerializer()

新しいXMLSerializerオブジェクトを構築する。

string = xmlSerializer.serializeToString(root)

rootをXMLにシリアル化した結果を返す。

rootをXMLにシリアル化できない場合、"InvalidStateError" DOMExceptionを投げる。

構築してからserializeToString()メソッドを呼び出す必要があるクラスとしてのXMLSerializerの設計は、不幸な歴史的成果物である。もし今日にこの機能を設計していたとしたら、それはスタンドアロン機能になっただろう。

[Exposed=Window]
interface XMLSerializer {
  constructor();

  DOMString serializeToString(Node root);
};

The new XMLSerializer() constructor steps are to do nothing.

The serializeToString(root) method steps are:

  1. Return the XML serialization of root given false.

8.6 HTMLサニタイゼーション

8.6.1 導入

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

ウェブアプリケーションでは、ユーザー生成コンテンツのレンダリングまたはクライアントサイドテンプレートの使用時など、信頼できないHTML文字列を処理する必要があることがよくある。これらの文字列をDOMに安全に挿入するには、DOMベースのクロスサイトスクリプティング(XSS)攻撃を防ぐために、慎重なサニタイゼーションが必要である。

HTMLサニタイゼーションは、HTML文字列を安全に解析し、サニタイズするためのネイティブなメカニズムを提供する。ユーザーエージェント独自のHTMLパーサーを使用することで、サニタイズされた出力が、ブラウザーがコンテンツをレンダリングする方法を正確に反映することを保証し、スクリプトの実行を防ぎ、スクリプトガジェットなどの高度な攻撃を軽減する。

これらのAPIは、HTMLを含む文字列をDOMツリーに解析し、解析時にそのマークアップをサニタイズする。この方法には、"安全"と"安全でない"という2つの主要なフレーバーがある。

8.6.1.1 安全および安全でない

"安全な"メソッドは、スクリプトを実行するマークアップを生成しない。つまり、これらはXSSから安全であることを目的としている。"安全でない"メソッドは、提供された構成に基づいて解析とフィルタリングを行うが、デフォルトでは同じ安全性を保証しない。

8.6.2 Sanitizerインターフェイス

[Exposed=Window]
interface Sanitizer {
  constructor(optional (SanitizerConfig or SanitizerPresets) configuration = "default");

  // Query configuration:
  SanitizerConfig get();

  // Modify a Sanitizer's lists and fields:
  boolean allowElement(SanitizerElementWithAttributes element);
  boolean removeElement(SanitizerElement element);
  boolean replaceElementWithChildren(SanitizerElement element);
  boolean allowProcessingInstruction(SanitizerPI pi);
  boolean removeProcessingInstruction(SanitizerPI pi);
  boolean allowAttribute(SanitizerAttribute attribute);
  boolean removeAttribute(SanitizerAttribute attribute);
  boolean setComments(boolean allow);
  boolean setDataAttributes(boolean allow);
  boolean setJavascriptURLs(boolean allow);

  // Remove markup that executes script.
  boolean removeUnsafe();
};
config = sanitizer.get()

サニタイザーのconfigurationを返す。

sanitizer.allowElement(element)

サニタイザーの設定で、指定された要素が許可されるようにする。

sanitizer.removeElement(element)

サニタイザーの設定が指定された要素をブロックするようにする。

sanitizer.replaceElementWithChildren(element)

指定された要素を削除するが、その子ノードを保持するようにサニタイザーを設定する。

sanitizer.allowAttribute(attribute)

指定された属性をグローバルに許可するようにサニタイザーを設定する。

sanitizer.removeAttribute(attribute)

指定された属性をグローバルにブロックするようにサニタイザーを設定する。

sanitizer.allowProcessingInstruction(pi)

指定された処理命令を許可するようにサニタイザーを設定する。

sanitizer.removeProcessingInstruction(pi)

指定された処理命令をブロックするようにサニタイザーを設定する。

sanitizer.setComments(allow)

コメントを保持するかどうかを設定する。

sanitizer.setDataAttributes(allow)

サニタイザーがカスタムデータ属性(たとえばdata-*)を保持するかどうかを設定する。

sanitizer.setJavascriptURLs(allow)

サニタイザーがjavascript: URLを含む属性を保持するかどうかを設定する。

sanitizer.removeUnsafe()

安全でないと見なされる要素および属性を自動的に削除するように設定を変更する。

A Sanitizer object has an associated configuration, which is a SanitizerConfig.

The new Sanitizer(configuration) constructor steps are:

  1. If configuration is a SanitizerPresets string:

    1. Assert: configuration is "default".

    2. Set configuration to the built-in safe default configuration.

  2. Configure this given configuration and true.

To configure a Sanitizer sanitizer, given a dictionary configuration and a boolean permissiveDefaults:

  1. Let freshConfiguration be a clone of configuration.

  2. Canonicalize the configuration freshConfiguration with permissiveDefaults.

  3. If freshConfiguration is not valid, then throw a TypeError.

  4. Set sanitizer's configuration to freshConfiguration.

To canonicalize the configuration SanitizerConfig configuration with a boolean permissiveDefaults:

  1. If neither configuration["elements"] nor configuration["removeElements"] exists, then set configuration["removeElements"] to an empty list.

  2. If neither configuration["attributes"] nor configuration["removeAttributes"] exists, then set configuration["removeAttributes"] to an empty list.

  3. If neither configuration["processingInstructions"] nor configuration["removeProcessingInstructions"] exists:

    1. If permissiveDefaults is true, then set configuration["removeProcessingInstructions"] to an empty list.

    2. Otherwise, set configuration["processingInstructions"] to an empty list.

  4. If configuration["elements"] exists:

    1. Let newElements be « ».

    2. For each element of configuration["elements"], append the result of canonicalizing element to newElements.

    3. Set configuration["elements"] to newElements.

  5. If configuration["removeElements"] exists, then set configuration["removeElements"] to the result of canonicalizing configuration["removeElements"].

  6. If configuration["attributes"] exists, then set configuration["attributes"] to the result of canonicalizing configuration["attributes"].

  7. If configuration["removeAttributes"] exists, then set configuration["removeAttributes"] to the result of canonicalizing configuration["removeAttributes"].

  8. If configuration["replaceWithChildrenElements"] exists, then set configuration["replaceWithChildrenElements"] to the result of canonicalizing configuration["replaceWithChildrenElements"].

  9. If configuration["processingInstructions"] exists, then set configuration["processingInstructions"] to the result of canonicalizing configuration["processingInstructions"].

  10. If configuration["removeProcessingInstructions"] exists, then set configuration["removeProcessingInstructions"] to the result of canonicalizing configuration["removeProcessingInstructions"].

  11. If configuration["comments"] does not exist, then set it to permissiveDefaults.

  12. If configuration["attributes"] exists and configuration["dataAttributes"] does not exist, then set it to permissiveDefaults.

  13. If configuration["javascriptURLs"] does not exist, then set it to permissiveDefaults.

To canonicalize a sanitizer list list:

  1. Let newList be « ».

  2. For each item in list, append the result of canonicalizing item to newList.

  3. Return newList.

To canonicalize a processing instruction list list:

  1. Let newList be « ».

  2. For each item in list, append the result of canonicalizing item to newList.

  3. Return newList.

To canonicalize a processing instruction given a SanitizerPI pi:

  1. If pi is a DOMString, then return «[ "target" → pi ]».

  2. Assert: pi is a dictionary and pi["target"] exists.

  3. Return «[ "target" → pi["target"] ]».

To canonicalize a sanitizer name given a DOMString or dictionary name, and a default namespace defaultNamespace (default null):

  1. If name is a DOMString, then return «[ "name" → name, "namespace" → defaultNamespace ]».

  2. Assert: name is a dictionary and both name["name"] and name["namespace"] exist.

  3. If name["namespace"] is the empty string, then set it to null.

  4. Return «[ "name" → name["name"], "namespace" → name["namespace"] ]».

To canonicalize a sanitizer element given a SanitizerElement element:

  1. Return the result of canonicalizing element with the HTML namespace as the default namespace.

To canonicalize a sanitizer element list list:

  1. Let newList be « ».

  2. For each item in list, append the result of canonicalizing item to newList.

  3. Return newList.

To find the canonicalized intersection of lists A and B:

  1. Let setA be « ».

  2. Let setB be « ».

  3. For each entry of A, append the result of canonicalizing entry to setA.

  4. For each entry of B, append the result of canonicalizing entry to setB.

  5. Return the intersection of setA and setB.

The get() method steps are:

Outside of the get() method, the order of the Sanitizer's elements and attributes is unobservable. By explicitly sorting the result of this method, we give implementations the opportunity to optimize by, for example, using unordered sets internally.

  1. Let config be this's configuration.

  2. Assert: config is valid.

  3. If config["elements"] exists:

    1. For each element of config["elements"]:

      1. If element["attributes"] exists, then set element["attributes"] to the result of sorting element["attributes"], with compare sanitizer items.

      2. If element["removeAttributes"] exists, then set element["removeAttributes"] to the result of sorting element["removeAttributes"], with compare sanitizer items.

    2. Set config["elements"] to the result of sorting config["elements"], with compare sanitizer items.

  4. Otherwise:

    1. Set config["removeElements"] to the result of sorting config["removeElements"], with compare sanitizer items.

  5. If config["replaceWithChildrenElements"] exists, then set config["replaceWithChildrenElements"] to the result of sorting config["replaceWithChildrenElements"], with compare sanitizer items.

  6. If config["processingInstructions"] exists, then set config["processingInstructions"] to the result of sorting config["processingInstructions"], with piA["target"] being code unit less than piB["target"].

  7. Otherwise:

    1. Set config["removeProcessingInstructions"] to the result of sorting config["removeProcessingInstructions"], with piA["target"] being code unit less than piB["target"].

  8. If config["attributes"] exists, then set config["attributes"] to the result of sorting config["attributes"] given compare sanitizer items.

  9. Otherwise:

    1. Set config["removeAttributes"] to the result of sorting config["removeAttributes"] given compare sanitizer items.

  10. Return config.

The allowElement(element) method steps are:

  1. Let configuration be this's configuration.

  2. Assert: configuration is valid.

  3. Set element to the result of canonicalizing element.

  4. If configuration["elements"] exists:

    1. Let modified be the result of removing element from configuration["replaceWithChildrenElements"].

    2. If configuration["attributes"] exists:

      1. If element["attributes"] exists:

        1. Set element["attributes"] to the result of creating a set from element["attributes"].

        2. Set element["attributes"] to the difference of element["attributes"] and configuration["attributes"].

        3. If configuration["dataAttributes"] is true, then remove all items item from element["attributes"] where item is a custom data attribute.

      2. If element["removeAttributes"] exists:

        1. Set element["removeAttributes"] to the result of creating a set from element["removeAttributes"].

        2. Set element["removeAttributes"] to the intersection of element["removeAttributes"] and configuration["attributes"].

    3. Otherwise:

      1. If element["attributes"] exists:

        1. Set element["attributes"] to the result of creating a set from element["attributes"].

        2. Set element["attributes"] to the difference of element["attributes"] and element["removeAttributes"] with default « ».

        3. Remove element["removeAttributes"].

        4. Set element["attributes"] to the difference of element["attributes"] and configuration["removeAttributes"].

      2. If element["removeAttributes"] exists:

        1. Set element["removeAttributes"] to the result of creating a set from element["removeAttributes"].

        2. Set element["removeAttributes"] to the difference of element["removeAttributes"] and configuration["removeAttributes"].

    4. If configuration["elements"] does not contain element:

      1. Append element to configuration["elements"].

      2. Return true.

    5. Let currentElement be the item in configuration["elements"] whose name member is element's name member and whose namespace member is element's namespace member.

    6. If element is equal to currentElement, then return modified.

    7. Remove element from configuration["elements"].

    8. Append element to configuration["elements"].

    9. Return true.

  5. Otherwise:

    1. If element["attributes"] exists or element["removeAttributes"] with default « » is not empty, then return false.

    2. Let modified be the result of removing element from configuration["replaceWithChildrenElements"].

    3. If configuration["removeElements"] does not contain element, then return modified.

    4. Remove element from configuration["removeElements"].

    5. Return true.

The removeElement(element) method steps are to return the result of removing element from this's configuration.

The replaceElementWithChildren(element) method steps are:

  1. Let configuration be this's configuration.

  2. Assert: configuration is valid.

  3. Set element to the result of canonicalizing element.

  4. If the built-in non-replaceable elements list contains element, then return false.

  5. Let modified be the result of removing element from configuration["elements"].

  6. If removing element from configuration["removeElements"] is true, then set modified to true.

  7. If configuration["replaceWithChildrenElements"] does not contain element:

    1. Append element to configuration["replaceWithChildrenElements"].

    2. Return true.

  8. Return modified.

The allowAttribute(attribute) method steps are:

  1. Let configuration be this's configuration.

  2. Assert: configuration is valid.

  3. Set attribute to the result of canonicalizing attribute.

  4. If configuration["attributes"] exists:

    1. If configuration["dataAttributes"] is true and attribute is a custom data attribute, then return false.

    2. If configuration["attributes"] contains attribute, then return false.

    3. If configuration["elements"] exists:

      1. For each element in configuration["elements"]:

        1. If element["attributes"] with default « » contains attribute, then remove attribute from element["attributes"].

    4. Append attribute to configuration["attributes"].

    5. Return true.

  5. Otherwise:

    1. If configuration["removeAttributes"] does not contain attribute, then return false.

    2. Remove attribute from configuration["removeAttributes"].

    3. Return true.

The removeAttribute(attribute) method steps are to return the result of removing attribute from this's configuration.

The setComments(allow) method steps are:

  1. Let configuration be this's configuration.

  2. Assert: configuration is valid.

  3. If configuration["comments"] is allow, then return false.

  4. Set configuration["comments"] to allow.

  5. Return true.

The setDataAttributes(allow) method steps are:

  1. Let configuration be this's configuration.

  2. Assert: configuration is valid.

  3. If configuration["attributes"] does not exist, then return false.

  4. If configuration["dataAttributes"] exists and is equal to allow, then return false.

  5. If allow is true:

    1. If configuration["elements"] exists:

      1. For each element of configuration["elements"]:

        1. If element["attributes"] exists, then remove all items item from element["attributes"] where item is a custom data attribute.

    2. Remove all items item from configuration["attributes"] where item is a custom data attribute.

  6. Set configuration["dataAttributes"] to allow.

  7. Return true.

The setJavascriptURLs(allow) method steps are:

  1. Let configuration be this's configuration.

  2. Assert: configuration is valid.

  3. If configuration["javascriptURLs"] is allow, then return false.

  4. Set configuration["javascriptURLs"] to allow.

  5. Return true.

The allowProcessingInstruction(pi) method steps are:

  1. Let configuration be this's configuration.

  2. Assert: configuration is valid.

  3. Set pi to the result of canonicalizing pi.

  4. If configuration["processingInstructions"] exists:

    1. If configuration["processingInstructions"] contains pi, then return false.

    2. Append pi to configuration["processingInstructions"].

    3. Return true.

  5. Otherwise:

    1. If configuration["removeProcessingInstructions"] contains pi:

      1. Remove pi from configuration["removeProcessingInstructions"].

      2. Return true.

    2. falseを返す。

The removeProcessingInstruction(pi) method steps are:

  1. Let configuration be this's configuration.

  2. Assert: configuration is valid.

  3. Set pi to the result of canonicalizing pi.

  4. If configuration["processingInstructions"] exists:

    1. If configuration["processingInstructions"] contains pi:

      1. Remove pi from configuration["processingInstructions"].

      2. Return true.

    2. falseを返す。

  5. Otherwise:

    1. If configuration["removeProcessingInstructions"] contains pi, then return false.

    2. Append pi to configuration["removeProcessingInstructions"].

    3. Return true.

The removeUnsafe() method steps are to return the result of removing unsafe from this's configuration.

8.6.3 サニタイザーの設定

dictionary SanitizerElementNamespace {
  required DOMString name;
  DOMString? _namespace = "http://www.w3.org/1999/xhtml";
};

// Used by "elements"
dictionary SanitizerElementNamespaceWithAttributes : SanitizerElementNamespace {
  sequence<SanitizerAttribute> attributes;
  sequence<SanitizerAttribute> removeAttributes;
};

dictionary SanitizerAttributeNamespace {
  required DOMString name;
  DOMString? _namespace = null;
};

dictionary SanitizerProcessingInstruction {
  required DOMString target;
};

typedef (DOMString or SanitizerElementNamespace) SanitizerElement;
typedef (DOMString or SanitizerElementNamespaceWithAttributes) SanitizerElementWithAttributes;
typedef (DOMString or SanitizerProcessingInstruction) SanitizerPI;
typedef (DOMString or SanitizerAttributeNamespace) SanitizerAttribute;

dictionary SanitizerConfig {
  sequence<SanitizerElementWithAttributes> elements;
  sequence<SanitizerElement> removeElements;
  sequence<SanitizerElement> replaceWithChildrenElements;

  sequence<SanitizerPI> processingInstructions;
  sequence<SanitizerPI> removeProcessingInstructions;

  sequence<SanitizerAttribute> attributes;
  sequence<SanitizerAttribute> removeAttributes;

  boolean comments;
  boolean dataAttributes;
  boolean javascriptURLs;
};

SanitizerElementNamespace、SanitizerAttributeNamespace、SanitizerElementNamespaceWithAttributes、およびSanitizerProcessingInstructionの各辞書は、マップの等価性に従って、同じメンバーを持ち、それらのメンバーが等しい場合に、等しい。

8.6.3.1 設定の不変条件

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

設定は、開発者が目的に合わせて変更することができ、また変更すべきである。オプションは、新しいSanitizerConfigディクショナリーを最初から作成するか、修飾子メソッドを使用して既存のSanitizerの設定を変更するか、既存のSanitizerの設定を辞書としてget()し、ディクショナリーを変更してから、それを使用して新しいSanitizerを作成することである。

空の設定はすべてを許可する(setHTMLUnsafe()のような"安全でない"メソッドで呼び出された場合)。設定"デフォルト"には、組み込みの安全なデフォルト設定が含まれる。"安全な"および"安全でない"サニタイザー方法は、異なるデフォルトを持つことに注意する。

すべての設定ディクショナリーが有効なわけではない。有効な設定は、冗長性(同じ要素を2回許可するように指定するなど)および矛盾(要素を削除して許可するように指定するなど)を回避する。

構成を有効にするには、いくつかの条件を満たす必要がある:

elements要素の許可リストでは、特定の要素の許可属性または除去属性を指定することもできる。これは、特定の要素に適用されるグローバル属性とローカル属性の両方を認識する、この標準の構造を反映することを意図している。グローバル属性とローカル属性は混在させることができるが、特定の属性が一方のリストで許可され、もう一方のリストで禁止されるような曖昧な設定は、一般に無効であることに注意する。

グローバルattributesグローバルremoveAttributes
ローカルattributes属性は、いずれかのリストに一致する場合に使用できる。重複は許可されない。属性は、ローカル許可リストにある場合にのみ許可される。グローバル除去とローカル許可リストの間で重複するエントリーは許可されない。グローバル除去リストは、この特定の要素に対しては機能しないが、ローカル許可リストを持たない他の要素には適用できることに注意する。
ローカルremoveAttributes属性は、グローバル許可リストにあって、ローカル除去リストにない場合に許可される。ローカル除去は、グローバル許可リストのサブセットである必要がある。属性は、どちらのリストにもない場合に使用できる。グローバル除去リストとローカル除去リストの間で重複するエントリーは許可されない。

グローバルリストと要素ごとのリストの間では、ほとんどの場合、重複が許可されないが、グローバル許可リストと要素ごとの除去リストの組み合わせでは、後者が前者のサブセットである必要があるという非対称性に注意する。重複だけに着目した、上記の表の抜粋を次に示す:

グローバルattributesグローバルremoveAttributes
ローカルattributes重複は許可されない。重複は許可されない。
ローカルremoveAttributesローカル除去は、グローバル許可リストのサブセットである必要がある。重複は許可されない。

dataAttributes設定は、カスタムデータ属性を許可する。dataAttributesを許可リストと見なす場合、上記の規則はカスタムデータ属性に簡単に拡張される:

グローバルattributesおよびdataAttributesの設定
ローカルattributesすべてのカスタムデータ属性が許可される。カスタムデータ属性は許可リストにリストできない。なぜなら、エントリーが重複することを意味するためである。
ローカルremoveAttributesローカル除去リストに含まれている場合を除き、カスタムデータ属性は許可される。カスタムデータ属性は、グローバル許可リストにリストできない。なぜなら、エントリーが重複していることを意味するためである。

これらの規則を言葉で表すと、次のようになる:

8.6.4 Sanitization algorithms

To get a sanitizer config from options given a SetHTMLOptions, SetHTMLUnsafeOptions, or ParseHTMLUnsafeOptions dictionary, or a TrustedHTMLParserOptions object options, and a boolean safe:

  1. Let sanitizerInput be null.

  2. If options is a TrustedHTMLParserOptions:

    1. If options's sanitizer configuration is null:

      1. Assert: safe is false.

      2. Return null.

    2. Set sanitizerInput to options's sanitizer configuration.

  3. Otherwise, if options["sanitizer"] exists, then set sanitizerInput to options["sanitizer"].

  4. Otherwise, if safe is false, then return null.

  5. Otherwise, set sanitizerInput to "default".

  6. Assert: sanitizerInput is either a Sanitizer instance, a SanitizerPresets member, or a SanitizerConfig dictionary.

  7. If sanitizerInput is a string:

    1. Assert: sanitizerInput is "default".

    2. Set sanitizerInput to the built-in safe default configuration.

  8. If sanitizerInput is a Sanitizer, then set sanitizerInput to sanitizerInput's configuration.

  9. Assert: sanitizerInput is a dictionary.

  10. Let sanitizer be a new Sanitizer object.

  11. Let permissiveDefaults be true if safe is false; false otherwise.

  12. Configure sanitizer given sanitizerInput and permissiveDefaults.

  13. Let configuration be sanitizer's configuration.

  14. If safe is true, then remove unsafe from configuration.

  15. Assert: configuration is valid.

  16. Return configuration.

    The returned SanitizerConfig is a fresh copy, so removing unsafe items from it never affects a Sanitizer object or SanitizerConfig dictionary that script can observe.

To determine whether a string value contains a javascript: URL:

  1. Let url be the result of running the basic URL parser on value.

  2. If url is failure, then return false.

  3. Return true if url's scheme is "javascript", and false otherwise.

To check if a sanitizer config allows comments given a SanitizerConfig configuration, return true if configuration["comments"] is true; otherwise false.

To check if a sanitizer config allows processing instruction target given a string piTarget and a SanitizerConfig configuration:

  1. Let pi be «[ "target" → piTarget ]».

  2. If configuration["processingInstructions"] exists, then return whether configuration["processingInstructions"] contains pi.

  3. If configuration["removeProcessingInstructions"] exists and configuration["removeProcessingInstructions"] contains pi, then return false.

  4. Return true.

A sanitizer action is one of the following:

To get the sanitizer action for an element name given a string localName, a string or null namespace, and a SanitizerConfig configuration:

  1. Let elementName be «[ "name" → localName, "namespace" → namespace ]».

  2. If configuration["replaceWithChildrenElements"] exists and configuration["replaceWithChildrenElements"] contains elementName, then return "Replace with children".

  3. If configuration["elements"] exists:

    1. If there is no item in configuration["elements"] whose name member is localName and whose namespace member is namespace, then return "Remove".

  4. Otherwise, if configuration["removeElements"] contains elementName, then return "Remove".

  5. Return "Keep".

To check if a sanitizer config allows an attribute given a string localName, a string or null namespace, a string value, a string elementLocalName, a string or null elementNamespace, and a SanitizerConfig configuration:

  1. Let attrName be «[ "name" → localName, "namespace" → namespace ]».

  2. Let elementName be «[ "name" → elementLocalName, "namespace" → elementNamespace ]».

  3. Let elementWithLocalAttributes be «[ ]».

  4. If configuration["elements"] exists and there is an item element in configuration["elements"] whose name member is elementLocalName and whose namespace member is elementNamespace, then set elementWithLocalAttributes to element.

  5. If elementWithLocalAttributes["removeAttributes"] exists and elementWithLocalAttributes["removeAttributes"] contains attrName, then return false.

  6. Otherwise, if configuration["attributes"] exists:

    1. If configuration["attributes"] does not contain attrName and elementWithLocalAttributes["attributes"] with default « » does not contain attrName, and if "data-" is not a code unit prefix of localName or namespace is not null or configuration["dataAttributes"] is not true, then return false.

  7. Otherwise:

    1. If elementWithLocalAttributes["attributes"] exists and elementWithLocalAttributes["attributes"] does not contain attrName, then return false.

    2. Otherwise, if configuration["removeAttributes"] exists and configuration["removeAttributes"] contains attrName, then return false.

  8. If configuration["javascriptURLs"] is true, then return true.

  9. If the pair (elementName, attrName) matches an entry in the built-in navigating URL attributes list, and if value contains a javascript: URL, then return false.

  10. If elementNamespace is the MathML namespace, localName is "href", namespace is null or the XLink namespace, and value contains a javascript: URL, then return false.

  11. If the built-in animating URL attributes list contains the pair (elementName, attrName), and value is "href" or "xlink:href", then return false.

  12. Return true.

To remove an element element from a SanitizerConfig configuration:

  1. Assert: configuration is valid.

  2. Set element to the result of canonicalizing element.

  3. Let modified be the result of removing element from configuration["replaceWithChildrenElements"].

  4. If configuration["elements"] exists:

    1. If configuration["elements"] contains element:

      1. Remove element from configuration["elements"].

      2. Return true.

    2. Return modified.

  5. Otherwise:

    1. If configuration["removeElements"] contains element, then return modified.

    2. Append element to configuration["removeElements"].

    3. Return true.

To remove an attribute attribute from a SanitizerConfig configuration:

  1. Assert: configuration is valid.

  2. Set attribute to the result of canonicalizing attribute.

  3. If configuration["attributes"] exists:

    1. Let modified be the result of removing attribute from configuration["attributes"].

    2. If configuration["elements"] exists:

      1. For each element of configuration["elements"]:

        1. If element["attributes"] with default « » contains attribute:

          1. Set modified to true.

          2. Remove attribute from element["attributes"].

        2. If element["removeAttributes"] with default « » contains attribute:

          1. Assert: modified is true.

          2. Remove attribute from element["removeAttributes"].

    3. Return modified.

  4. Otherwise:

    1. If configuration["removeAttributes"] contains attribute, then return false.

    2. If configuration["elements"] exists:

      1. For each element in configuration["elements"]:

        1. If element["attributes"] with default « » contains attribute, then remove attribute from element["attributes"].

        2. If element["removeAttributes"] with default « » contains attribute, then remove attribute from element["removeAttributes"].

    3. Append attribute to configuration["removeAttributes"].

    4. Return true.

To remove unsafe from a SanitizerConfig configuration:

  1. Assert: configuration is valid.

  2. Let result be false.

  3. For each element in built-in safe baseline configuration["removeElements"]:

    1. If removing element from configuration is true, then set result to true.

  4. For each attribute in built-in safe baseline configuration["removeAttributes"]:

    1. If removing attribute from configuration is true, then set result to true.

  5. For each attribute that is an event handler content attribute:

    1. If removing attribute from configuration is true, then set result to true.

  6. If configuration["javascriptURLs"] is true:

    1. Set result to true.

    2. Set configuration["javascriptURLs"] to false.

  7. Return result.

To compare sanitizer items itemA and itemB:

  1. Let namespaceA be itemA["namespace"].

  2. Let namespaceB be itemB["namespace"].

  3. If namespaceA is null:

    1. If namespaceB is not null, then return true.

  4. Otherwise:

    1. If namespaceB is null, then return false.

    2. If namespaceA is code unit less than namespaceB, then return true.

    3. If namespaceA is not namespaceB, then return false.

  5. If itemA["name"] is code unit less than itemB["name"], then return true.

  6. falseを返す。

To canonicalize a SanitizerElementWithAttributes element:

  1. Let result be the result of canonicalizing element.

  2. If element is a dictionary:

    1. If element["attributes"] exists, then set result["attributes"] to the result of canonicalizing element["attributes"].

    2. If element["removeAttributes"] exists, then set result["removeAttributes"] to the result of canonicalizing element["removeAttributes"].

  3. If neither result["attributes"] nor result["removeAttributes"] exists, then set result["removeAttributes"] to an empty list.

  4. Return result.

To determine whether a canonical SanitizerConfig config is valid:

It's expected that the configuration being passed in has previously been run through the canonicalize the configuration steps. We will simply assert conditions that that algorithm is guaranteed to hold.

  1. Assert: config["elements"] exists or config["removeElements"] exists.

  2. If config["elements"] exists and config["removeElements"] exists, then return false.

  3. Assert: Either config["processingInstructions"] exists or config["removeProcessingInstructions"] exists.

  4. If config["processingInstructions"] exists and config["removeProcessingInstructions"] exists, then return false.

  5. Assert: Either config["attributes"] exists or config["removeAttributes"] exists.

  6. If config["attributes"] exists and config["removeAttributes"] exists, then return false.

  7. Assert: All SanitizerElementNamespaceWithAttributes, SanitizerElementNamespace, SanitizerProcessingInstruction, and SanitizerAttributeNamespace items in config are canonical, meaning they have been run through canonicalizing, as appropriate.

  8. If config["elements"] exists:

    1. If config["elements"] has duplicates, then return false.

  9. Otherwise:

    1. If config["removeElements"] has duplicates, then return false.

  10. If config["replaceWithChildrenElements"] exists and has duplicates, then return false.

  11. If config["processingInstructions"] exists:

    1. If config["processingInstructions"] has duplicates, then return false.

  12. Otherwise:

    1. If config["removeProcessingInstructions"] has duplicates, then return false.

  13. If config["attributes"] exists:

    1. If config["attributes"] has duplicates, then return false.

  14. Otherwise:

    1. If config["removeAttributes"] has duplicates, then return false.

  15. If config["replaceWithChildrenElements"] exists:

    1. For each element of config["replaceWithChildrenElements"]:

      1. If the built-in non-replaceable elements list contains element, then return false.

    2. If config["elements"] exists:

      1. If the intersection of config["elements"] and config["replaceWithChildrenElements"] is not empty, then return false.

    3. Otherwise:

      1. If the intersection of config["removeElements"] and config["replaceWithChildrenElements"] is not empty, then return false.

  16. If config["attributes"] exists:

    1. Assert: config["dataAttributes"] exists.

    2. If config["elements"] exists:

      1. For each element of config["elements"]:

        1. If element["attributes"] exists and element["attributes"] has duplicates, then return false.

        2. If element["removeAttributes"] exists and element["removeAttributes"] has duplicates, then return false.

        3. If the intersection of config["attributes"] and element["attributes"] with default « » is not empty, then return false.

        4. If element["removeAttributes"] with default « » is not a subset of config["attributes"], then return false.

        5. If config["dataAttributes"] is true and element["attributes"] contains a custom data attribute, then return false.

    3. If config["dataAttributes"] is true and config["attributes"] contains a custom data attribute, then return false.

  17. Otherwise:

    1. If config["elements"] exists:

      1. For each element of config["elements"]:

        1. If element["attributes"] exists and element["removeAttributes"] exists, then return false.

        2. If element["attributes"] exists and element["attributes"] has duplicates, then return false.

        3. If element["removeAttributes"] exists and element["removeAttributes"] has duplicates, then return false.

        4. If the intersection of config["removeAttributes"] and element["attributes"] with default « » is not empty, then return false.

        5. If the intersection of config["removeAttributes"] and element["removeAttributes"] with default « » is not empty, then return false.

    2. If config["dataAttributes"] exists, then return false.

  18. Return true.

8.6.5 サニタイゼーション定数

要素のサニタイゼーションカテゴリーは、次のいずれかになる:

デフォルト
要素ははデフォルトのSanitizerConfigに含まれる。
安全でない
要素はXSSになる可能性がある。(そのような要素は、setHTMLUnsafe()またはparseHTMLUnsafe()によって保持され、setHTML()、parseHTML()およびremoveUnsafe()によって削除される。
未分類
この要素はデフォルトでは削除もインクルードもされないが、まだSanitizerConfigに追加することはできる。

The built-in safe baseline configuration is a SanitizerConfig. Its removeElements list consists of all HTML elements normatively marked as Unsafe within their individual definitions, along with the obsolete frame element, and the SVG script and SVG use elements, and its removeAttributes list is empty.

Event handler content attributes are automatically removed by the remove unsafe algorithm during safe sanitization, so the effective baseline behaves as if they were included in the removeAttributes list.

The built-in safe default configuration is a SanitizerConfig whose members are initialized as follows:

processingInstructions
« »
attributes
A list consisting of:
comments
false
dataAttributes
false
javascriptURLs
false
elements
All HTML elements normatively categorized as Default within their individual definitions, alongside the MathML and SVG elements listed in the table below. Attributes included in those definitions are included in each element's respective attributes list.

The following table lists the MathML and SVG elements that are categorized as Default in the built-in safe default configuration, represented as a list of SanitizerElementNamespaceWithAttributes dictionaries. For each row in the table, the "Element" column corresponds to the name member, the "Namespace" column corresponds to the namespace member, and the "Allowed attributes" column corresponds to the attributes member (where each listed attribute is represented as a SanitizerAttribute in the sequence):

要素名前空間Allowed attributes
aMathMLhref, hreflang, type
mathMathML
merrorMathML
mfracMathML
miMathML
mmultiscriptsMathML
mnMathML
moMathMLfence, form, largeop, lspace, maxsize, minsize, movablelimits, rspace, separator, stretchy, symmetric
moverMathMLaccent
mpaddedMathMLdepth, height, lspace, voffset, width
mphantomMathML
mprescriptsMathML
mrootMathML
mrowMathML
msMathML
mspaceMathMLdepth, height, width
msqrtMathML
mstyleMathML
msubMathML
msubsupMathML
msupMathML
mtableMathML
mtdMathMLcolumnspan, rowspan
mtextMathML
mtrMathML
munderMathMLaccentunder
munderoverMathMLaccent, accentunder
semanticsMathML
aSVGhref, hreflang, type
circleSVGcx, cy, pathLength, r
defsSVG
descSVG
ellipseSVGcx, cy, pathLength, rx, ry
foreignObjectSVGheight, width, x, y
gSVG
lineSVGpathLength, x1, x2, y1, y2
markerSVGmarkerHeight, markerUnits, markerWidth, orient, preserveAspectRatio, refX, refY, viewBox
metadataSVG
パスSVGd, pathLength
polygonSVGpathLength, points
polylineSVGpathLength, points
rectSVGheight, pathLength, rx, ry, width, x, y
svgSVGheight, preserveAspectRatio, viewBox, width, x, y
textSVGdx, dy, lengthAdjust, rotate, textLength, x, y
textPathSVGlengthAdjust, method, path, side, spacing, startOffset, textLength
titleSVG
tspanSVGdx, dy, lengthAdjust, rotate, textLength, x, y

The built-in navigating URL attributes list corresponds to all HTML elements marked with navigating URL attributes in their normative definitions, as well as the element-attribute pairs represented in the following table. For each row in the table, the element corresponds to a SanitizerElementNamespace whose name member is given by the "Element" column and whose namespace member is given by the "Element namespace" column; and the attribute corresponds to a SanitizerAttributeNamespace whose name member is given by the "Attribute" column and whose namespace member is given by the "Attribute namespace" column:

要素Element namespace属性Attribute namespace
aSVGhrefno namespace
aSVGhrefXLink

The MathML a element is not listed here because the sanitizer config allows an attribute algorithm disallows an href attribute that contains a javascript: URL on any MathML element, whether the attribute is in no namespace or in the XLink namespace.

The built-in animating URL attributes list is the list of element-attribute pairs represented by the following table. For each row in the table, the element corresponds to a SanitizerElementNamespace whose name member is given by the "Element" column and whose namespace member is given by the "Element namespace" column; and the attribute corresponds to a SanitizerAttributeNamespace whose name member is given by the "Attribute" column and whose namespace member is null:

要素Element namespace属性
animateSVGattributeName
animateTransformSVGattributeName
setSVGattributeName

The built-in non-replaceable elements list contains elements that must not be replaced with their children, as doing so can lead to re-parsing issues or an invalid node tree. It is the following list of SanitizerElementNamespace dictionaries, represented by the table below. For each row in the table, the "Element" column corresponds to the name member, and the "Element namespace" column corresponds to the namespace member:

要素Element namespace
htmlHTML
svgSVG
mathMathML

8.6.6 セキュリティの考慮事項

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

サニタイザーAPIは、提供されたHTMLコンテンツが解析される際に、指定された設定に従って要素および属性を除去することで、DOMベースのクロスサイトスクリプティングを防止することを意図している。By design, the setHTML(), streamHTML(), and parseHTML() methods remove script-capable markup regardless of the configuration supplied; if any configuration could preserve such markup through these methods, that would be a bug.

By contrast, unsafe HTML parsing methods (such as setHTMLUnsafe(), streamHTMLUnsafe(), and parseHTMLUnsafe()) and legacy HTML sinks (such as innerHTML, outerHTML, and insertAdjacentHTML()) only sanitize when a sanitizer is supplied via options or a Trusted Types default policy's createParserOptions callback. Because a default policy's createParserOptions callback is invoked for these sinks instead of createHTML, defining a createParserOptions callback that passes options through without a sanitizer will leave innerHTML, streamHTMLUnsafe(), and related sinks unsanitized even if the policy's createHTML callback sanitizes strings. Similarly, enabling runScripts in createParserOptions will cause scripts inserted via streamHTMLUnsafe(), innerHTML, outerHTML, and insertAdjacentHTML() to execute.

しかし、サニタイザーAPIでは防ぐことができないセキュリティ上の問題がある。次のセクションでは、それらについて説明する。

8.6.6.1 サーバー側で反映および保存されたXSS

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

サニタイザーAPIはDOM内のみで動作し、HTMLコンテンツがノードツリーに解析される際にそれをフィルタリングする機能を追加する。サニタイザーAPIは、サーバー側で反映または保存されたXSSには対応していない。

8.6.6.2 DOMクローバリング

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

DOMクローバリングとは、悪意のあるHTMLがidまたはname属性を使用してアプリケーションを混乱させ、HTML要素のchildrenプロパティなどのDOMプロパティを悪意のあるコンテンツによってシャドウイング(上書き)してしまう攻撃のことである。

サニタイザーAPIは、デフォルトではDOMクローバリング攻撃から保護しないが、idおよびname属性を削除するように設定できる。

8.6.6.3 スクリプトガジェットを使用するXSS

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

スクリプトガジェットは、攻撃者が広く使われているJavaScriptライブラリーの既存のアプリケーションコードを使用して、独自のコードを実行させる手法である。これは多くの場合、無害に見えるコード、またはフレームワークによって解析および解釈されるだけの外見上は不活性なDOMノードを注入し、その入力に基づいてJavaScriptを実行することによって行われる。

サニタイザーAPIは、これらの攻撃を防ぐことができない。その代わりに、著者が一般的に未知の要素を明示的に許可することに加えて、data-*およびslot属性ならびにslotおよびtemplateのような要素など、テンプレートおよびフレームワーク固有のコードに一般に使用される属性、要素、およびマークアップを明示的に許可することに依存している。これらの制限はすべてを網羅しているわけではなく、著者はこの動作についてサードパーティのライブラリを調査することを推奨する。

8.6.6.4 ミューテーションXSS

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

ミューテーションXSSまたはmXSSは、解析されたDOM構造がシリアル化と再解析の後に同じでない場合につけこんで、シリアル化前に発生するサニタイゼーションをバイパスする攻撃を説明する。そのような攻撃を実行するための例は、外来コンテンツまたは誤ってネストされたタグの解析動作の変更に依存することである。

サニタイザーAPIは、文字列をノードツリーに変換する関数のみを提供する。The context is supplied implicitly by all sanitizer functions: setHTML(), appendHTML(), prependHTML(), streamHTML(), streamAppendHTML(), and streamPrependHTML() use the element they're called on (or, for a shadow root, its host); beforeHTML(), afterHTML(), replaceWithHTML(), streamBeforeHTML(), streamAfterHTML(), and streamReplaceWithHTML() use the parent (or, for a shadow root or template contents, its host); and Document.parseHTML() creates a new document. したがって、サニタイザーAPIはミューテーションXSSの影響を直接受けない。

もし開発者がサニタイズされたノードツリーをinnerHTMLなどを介して文字列として取得し、再度解析するならば、ミューテーションXSSが発生する可能性がある。この行為は、強く推奨しない。結局のところ、HTMLを文字列として処理または渡す必要がある場合、文字列は信頼できないと見なされ、DOMに挿入されるときに再サニタイズされる。言い換えれば、サニタイズされてからシリアル化されたHTMLツリーは、もはやサニタイズされたとは見なされない。mXSSのより完全な処置については、[MXSS]を参照。