Living Standard — Last Updated 2 October 2026
APIs for dynamically inserting markup into the document interact with the parser, and thus their behavior varies depending on whether they are used with HTML documents (and the HTML parser) or XML documents (and the XML parser).
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.
document = document.open()Support in all current engines.
Causes the Document to be replaced in-place, as if it was a new
Document object, but reusing the previous object, which is then returned.
The resulting Document has an HTML parser associated with it, which can be given
data to parse using document.write().
The method has no effect if the Document is still being parsed.
Throws an "InvalidStateError" DOMException if the
Document is an XML document.
Throws an "InvalidStateError" DOMException if the
parser is currently executing a custom element constructor.
window = document.open(url, name, features)Works like the window.open() method.
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. It is initially false.
The document open steps, given a document, are as follows:
If document is an XML document, then throw
an "InvalidStateError" DOMException.
If document's throw-on-dynamic-markup-insertion counter is greater
than 0, then throw an "InvalidStateError"
DOMException.
Let entryDocument be the entry global object's associated Document.
If document's origin is not
same origin to entryDocument's origin, then throw a
"SecurityError" DOMException.
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.
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.
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.
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.
For each shadow-including inclusive descendant node of document, erase all event listeners and handlers given node.
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.
Replace all with null within document.
If document is fully active:
Let newURL be a copy of entryDocument's URL.
If entryDocument is not document, then set newURL's fragment to null.
Run the URL and history update steps with document and newURL.
Set document's is initial about:blank to
false.
If document's iframe load in progress flag is set, then set document's mute iframe load flag.
Set document to no-quirks mode.
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, and that the tokenizer will wait for
an explicit call to document.close() before emitting an
end-of-file token). The encoding confidence is
irrelevant.
Set the insertion point to point at just before the end of the input stream (which at this point will be empty).
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.
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:
If this is not fully active, then throw an
"InvalidAccessError" DOMException.
Return the result of running the window open steps with url, name, and features.
document.close()Support in all current engines.
Closes the input stream that was opened by the document.open() method.
Throws an "InvalidStateError" DOMException if the
Document is an XML document.
Throws an "InvalidStateError" DOMException if the
parser is currently executing a custom element constructor.
The close() method must run the following
steps:
If this is an XML document, then throw
an "InvalidStateError" DOMException.
If this's throw-on-dynamic-markup-insertion counter is greater
than zero, then throw an "InvalidStateError"
DOMException.
If there is no script-created parser associated with this, then return.
Insert an explicit "EOF" character at the end of the parser's input stream.
If this's pending parsing-blocking script is not null, then return.
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.
document.write()document.write(...text)Support in all current engines.
In general, adds the given string(s) to the Document's input stream.
This method has very idiosyncratic behavior. In some cases, this method can
affect the state of the HTML parser while the parser is running, resulting in a DOM
that does not correspond to the source of the document (e.g. if the string written is the string
"<plaintext>" or "<!--"). In other cases,
the call can clear the current page first, as if document.open() had been called. In yet more cases, the method
is simply ignored, or throws an exception. User agents are explicitly allowed to avoid executing
script elements inserted via this method. And to make matters even worse, the
exact behavior of this method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use
of this method is strongly discouraged.
Throws an "InvalidStateError" DOMException when
invoked on XML documents.
Throws an "InvalidStateError" DOMException if the
parser is currently executing a custom element constructor.
This method performs no sanitization to remove potentially-dangerous elements
and attributes like script or event handler content attributes.
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:
Let string be the empty string.
Let isTrusted be false if text contains a string; otherwise true.
For each value of text:
If value is a TrustedHTML object, then
append value's associated data to
string.
Otherwise, append value to string.
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".
If lineFeed is true, append U+000A LINE FEED to string.
If document is an XML document, then throw
an "InvalidStateError" DOMException.
If document's throw-on-dynamic-markup-insertion counter is greater
than 0, then throw an "InvalidStateError"
DOMException.
If document's active parser was aborted is true, then return.
If the insertion point is undefined:
If document's unload counter is greater than 0 or document's ignore-destructive-writes counter is greater than 0, then return.
Run the document open steps with document.
Insert string into the input stream just before the insertion point.
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).
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".
document.writeln()document.writeln(...text)Support in all current engines.
Adds the given string(s) to the Document's input stream, followed by a newline
character. If necessary, calls the open() method
implicitly first.
This method has very idiosyncratic behavior. Use of this
method is strongly discouraged, for the same reasons as document.write().
Throws an "InvalidStateError" DOMException when
invoked on XML documents.
Throws an "InvalidStateError" DOMException if the
parser is currently executing a custom element constructor.
This method performs no sanitization to remove potentially-dangerous elements
and attributes like script or event handler content attributes.
The document.writeln(...text) method steps are
to run the document write steps with this, text, true, and
"Document writeln".
Support in all current engines.
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 = [];
};
DOMParser interfaceThe DOMParser interface allows authors to create new Document objects
by parsing strings, as either HTML or XML.
parser = new DOMParser()Support in all current engines.
Constructs a new DOMParser object.
document = parser.parseFromString(string, type)Support in all current engines.
Parses string using either the HTML or XML parser, according to type,
and returns the resulting Document. type can be "text/html"
(which will invoke the HTML parser), or any of "text/xml",
"application/xml", "application/xhtml+xml", or
"image/svg+xml" (which will invoke the XML parser).
For the XML parser, if string cannot be parsed, then the returned
Document will contain elements describing the resulting error.
Note that script elements are not evaluated during parsing, and the resulting
document's encoding will always be
UTF-8. The document's URL will be
inherited from parser's relevant global object.
Values other than the above for type will cause a TypeError exception
to be thrown.
The design of DOMParser, as a class that needs to be constructed and
then have its parseFromString() method
called, is an unfortunate historical artifact. If we were designing this functionality today it
would be a standalone function. For parsing HTML, the modern alternative is Document.parseHTMLUnsafe().
This method performs no sanitization to remove potentially-dangerous elements
and attributes like script or event handler content attributes.
[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:
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".
Let relevantDocument be this's relevant global
object's associated
Document.
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.
Switch on type:
text/html"Parse HTML from a string given document and compliantString.
Since document does not have a browsing context, scripting is disabled.
Create an XML parser parser, associated with document, and with XML scripting support disabled.
Parse compliantString using parser.
If the previous step resulted in an XML well-formedness or XML namespace well-formedness error:
Assert: document has no child nodes.
Let root be the result of creating an
element given document, "parsererror", and "http://www.mozilla.org/newlayout/xml/parsererror.xml".
Optionally, add attributes or children to root to describe the nature of the parsing error.
Append root to document.
Return document.
To parse HTML from a string, given a Document document, a
string html, and an optional SanitizerConfig or null
configuration (default null):
Set document's type to "html".
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.
Place html into the input stream for parser. The encoding confidence is irrelevant.
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.
element.setHTML(html, options)Parses html using the HTML parser with the given options, and
replaces the children of element (or the template contents in the case of
a template element) with the result. element provides context for the
HTML parser. The parsed fragment is sanitized based on
options's sanitizer member, and
unsafe content is removed. Does nothing if
element is an HTML or SVG script element.
shadowRoot.setHTML(html, options)Parses html using the HTML parser with the given options, and
replaces the children of shadowRoot with the result. shadowRoot's host provides context for the HTML parser. The
parsed fragment is sanitized based on options's sanitizer member, and unsafe content is removed.
element.appendHTML(html, options)Parses html using the HTML parser with the given options, and
inserts the result after the last child of element (or the template
contents in the case of a template element). element provides
context for the HTML parser. The parsed fragment is sanitized
based on options's sanitizer
member, and unsafe content is removed. Does
nothing if element is an HTML or SVG script element.
shadowRoot.appendHTML(html, options)Parses html using the HTML parser with the given options, and
inserts the result after the last child of shadowRoot. shadowRoot's host provides context for the HTML parser. The
parsed fragment is sanitized based on options's sanitizer member, and unsafe content is removed.
element.prependHTML(html, options)Parses html using the HTML parser with the given options, and
inserts the result before the first child of element (or the template
contents in the case of a template element). element provides
context for the HTML parser. The parsed fragment is sanitized
based on options's sanitizer
member, and unsafe content is removed. Does
nothing if element is an HTML or SVG script element.
shadowRoot.prependHTML(html, options)Parses html using the HTML parser with the given options, and
inserts the result before the first child of shadowRoot. shadowRoot's host provides context for the HTML parser. The
parsed fragment is sanitized based on options's sanitizer member, and unsafe content is removed.
childNode.beforeHTML(html, options)Parses html using the HTML parser with the given options, and
inserts the result before childNode. childNode's parent (or, if that parent
is a shadow root or template contents, its host) provides context for the HTML parser. The
parsed fragment is sanitized based on options's sanitizer member, and unsafe content is removed. Does nothing if
childNode has no parent, or if its parent is an HTML or SVG script
element. Throws a "HierarchyRequestError" DOMException if
the parent is a Document, a template element, or a
DocumentFragment without a host.
childNode.afterHTML(html, options)Parses html using the HTML parser with the given options, and
inserts the result after childNode. childNode's parent (or, if that parent
is a shadow root or template contents, its host) provides context for the HTML parser. The
parsed fragment is sanitized based on options's sanitizer member, and unsafe content is removed. Does nothing if
childNode has no parent, or if its parent is an HTML or SVG script
element. Throws a "HierarchyRequestError" DOMException if
the parent is a Document, a template element, or a
DocumentFragment without a host.
childNode.replaceWithHTML(html, options)Parses html using the HTML parser with the given options, and
replaces childNode with the result. childNode's parent (or, if that parent
is a shadow root or template contents, its host) provides context for the HTML parser. The
parsed fragment is sanitized based on options's sanitizer member, and unsafe content is removed. Does nothing if
childNode has no parent, or if its parent is an HTML or SVG script
element. Throws a "HierarchyRequestError" DOMException if
the parent is a Document, a template element, or a
DocumentFragment without a host.
element.setHTMLUnsafe(html, options)Parses html using the HTML parser with the given options, and
replaces the children of element (or the template contents in the case of
a template element) with the result. element provides context for the
HTML parser. If options is a SetHTMLUnsafeOptions dictionary containing a
sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragment before it is
inserted into element. If options's runScripts is true, scripts contained in
html will be executed immediately after the node tree is updated (unless altered by a
Trusted Types default policy). Throws a TypeError if Trusted Types are enforced and
either html is not a TrustedHTML object (and no
default policy converts it) or options is not a TrustedHTMLParserOptions object and no default policy
defines createParserOptions.
shadowRoot.setHTMLUnsafe(html, options)Parses html using the HTML parser with the given options, and
replaces the children of shadowRoot with the result. shadowRoot's host provides context for the HTML parser. If
options is a SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragment before it is
inserted into shadowRoot. If options's runScripts is true, scripts contained in
html will be executed immediately after the node tree is updated (unless altered by a
Trusted Types default policy). Throws a TypeError if Trusted Types are enforced and
either html is not a TrustedHTML object (and no
default policy converts it) or options is not a TrustedHTMLParserOptions object and no default policy
defines createParserOptions.
element.appendHTMLUnsafe(html, options)Parses html using the HTML parser with the given options, and
inserts the result after the last child of element (or the template
contents in the case of a template element). element provides
context for the HTML parser. If options is a SetHTMLUnsafeOptions
dictionary containing a sanitizer member
or a TrustedHTMLParserOptions object with a
non-null sanitizer configuration, it is used to sanitize the parsed fragment before
it is inserted into element. If options's runScripts is true, scripts contained in
html will be executed immediately after the node tree is updated (unless altered by a
Trusted Types default policy). Throws a TypeError if Trusted Types are enforced and
either html is not a TrustedHTML object (and no
default policy converts it) or options is not a TrustedHTMLParserOptions object and no default policy
defines createParserOptions.
shadowRoot.appendHTMLUnsafe(html, options)Parses html using the HTML parser with the given options, and
inserts the result after the last child of shadowRoot. shadowRoot's host provides context for the HTML parser. If
options is a SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragment before it is
inserted into shadowRoot. If options's runScripts is true, scripts contained in
html will be executed immediately after the node tree is updated (unless altered by a
Trusted Types default policy). Throws a TypeError if Trusted Types are enforced and
either html is not a TrustedHTML object (and no
default policy converts it) or options is not a TrustedHTMLParserOptions object and no default policy
defines createParserOptions.
element.prependHTMLUnsafe(html, options)Parses html using the HTML parser with the given options, and
inserts the result before the first child of element (or the template
contents in the case of a template element). element provides
context for the HTML parser. If options is a SetHTMLUnsafeOptions
dictionary containing a sanitizer member
or a TrustedHTMLParserOptions object with a
non-null sanitizer configuration, it is used to sanitize the parsed fragment before
it is inserted into element. If options's runScripts is true, scripts contained in
html will be executed immediately after the node tree is updated (unless altered by a
Trusted Types default policy). Throws a TypeError if Trusted Types are enforced and
either html is not a TrustedHTML object (and no
default policy converts it) or options is not a TrustedHTMLParserOptions object and no default policy
defines createParserOptions.
shadowRoot.prependHTMLUnsafe(html, options)Parses html using the HTML parser with the given options, and
inserts the result before the first child of shadowRoot. shadowRoot's host provides context for the HTML parser. If
options is a SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragment before it is
inserted into shadowRoot. If options's runScripts is true, scripts contained in
html will be executed immediately after the node tree is updated (unless altered by a
Trusted Types default policy). Throws a TypeError if Trusted Types are enforced and
either html is not a TrustedHTML object (and no
default policy converts it) or options is not a TrustedHTMLParserOptions object and no default policy
defines createParserOptions.
childNode.beforeHTMLUnsafe(html, options)Parses html using the HTML parser with the given options, and
inserts the result before childNode. childNode's parent (or, if that parent
is a shadow root or template contents, its host) provides context for the HTML parser. If
options is a SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragment before it is
inserted into the node tree. If options's runScripts is true, scripts contained in
html will be executed immediately after the node tree is updated (unless altered by a
Trusted Types default policy). Does nothing if childNode has no parent. Throws a
"HierarchyRequestError" DOMException if the parent is a
Document, a template element, or a DocumentFragment
without a host. Throws a
TypeError if Trusted Types are enforced and either html is not a TrustedHTML object (and no default policy converts it) or
options is not a TrustedHTMLParserOptions object and no default policy
defines createParserOptions.
childNode.afterHTMLUnsafe(html, options)Parses html using the HTML parser with the given options, and
inserts the result after childNode. childNode's parent (or, if that parent
is a shadow root or template contents, its host) provides context for the HTML parser. If
options is a SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragment before it is
inserted into the node tree. If options's runScripts is true, scripts contained in
html will be executed immediately after the node tree is updated (unless altered by a
Trusted Types default policy). Does nothing if childNode has no parent. Throws a
"HierarchyRequestError" DOMException if the parent is a
Document, a template element, or a DocumentFragment
without a host. Throws a
TypeError if Trusted Types are enforced and either html is not a TrustedHTML object (and no default policy converts it) or
options is not a TrustedHTMLParserOptions object and no default policy
defines createParserOptions.
childNode.replaceWithHTMLUnsafe(html, options)Parses html using the HTML parser with the given options, and
replaces childNode with the result. childNode's parent (or, if that parent
is a shadow root or template contents, its host) provides context for the HTML parser. If
options is a SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragment before it is
inserted into the node tree. If options's runScripts is true, scripts contained in
html will be executed immediately after the node tree is updated (unless altered by a
Trusted Types default policy). Does nothing if childNode has no parent. Throws a
"HierarchyRequestError" DOMException if the parent is a
Document, a template element, or a DocumentFragment
without a host. Throws a
TypeError if Trusted Types are enforced and either html is not a TrustedHTML object (and no default policy converts it) or
options is not a TrustedHTMLParserOptions object and no default policy
defines createParserOptions.
doc = Document.parseHTML(html, options)Parses html using the HTML parser with the given options, and
returns a new Document containing the result. The resulting document is sanitized based on options's sanitizer member, and unsafe content is removed.
doc = Document.parseHTMLUnsafe(html, options)Parses html using the HTML parser with the given options, and returns
the resulting Document.
Note that script elements are not evaluated during parsing, and the resulting
document's encoding will always be
UTF-8. The document's URL will be
about:blank. If options is a ParseHTMLUnsafeOptions
dictionary containing a sanitizer
member or a TrustedHTMLParserOptions object
with a non-null sanitizer configuration, it is used to sanitize the resulting DOM.
Throws a TypeError if Trusted Types are enforced and either html is not
a TrustedHTML object (and no default policy converts it) or
options is not a TrustedHTMLParserOptions object and no default
policy defines createParserOptions.
By default, the methods with an Unsafe suffix perform no
sanitization to remove potentially-dangerous elements and attributes like script or
event handler content attributes.
Element's setHTML(html, options) method
steps are:
Let target be the target for HTML insertion given this.
Filter and set HTML given target, html, options, and Safe.
Element's appendHTML(html, options)
method steps are:
Let target be the target for HTML insertion given this.
Filter and pre-insert HTML given target, null, html, options, and Safe.
Element's prependHTML(html, options)
method steps are:
Let target be the target for HTML insertion given this.
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.
NonDocumentTypeChildNode's beforeHTML(html,
options) method steps are:
Let parent be the parent for HTML insertion given this.
If parent is null, then return.
Filter and pre-insert HTML given parent, this, html, options, and Safe.
NonDocumentTypeChildNode's afterHTML(html,
options) method steps are:
Let parent be the parent for HTML insertion given this.
If parent is null, then return.
Filter and pre-insert HTML given parent, this's next sibling, html, options, and Safe.
NonDocumentTypeChildNode's replaceWithHTML(html,
options) method steps are:
Let parent be the parent for HTML insertion given this.
If parent is null, then return.
Filter and replace with HTML given parent, this, html, options, and Safe.
Element's setHTMLUnsafe(html, options)
method steps are:
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".
Let target be the target for HTML insertion given this.
Filter and set HTML given target, compliantHTML, compliantOptions, and Unsafe.
Element's appendHTMLUnsafe(html,
options) method steps are:
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".
Let target be the target for HTML insertion given this.
Filter and pre-insert HTML given target, null, compliantHTML, compliantOptions, and Unsafe.
Element's prependHTMLUnsafe(html,
options) method steps are:
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".
Let target be the target for HTML insertion given this.
Filter and pre-insert HTML given target, target's first child, compliantHTML, compliantOptions, and Unsafe.
ShadowRoot's setHTMLUnsafe(html,
options) method steps are:
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".
Filter and set HTML given this, compliantHTML, compliantOptions, and Unsafe.
ShadowRoot's appendHTMLUnsafe(html,
options) method steps are:
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".
Filter and pre-insert HTML given this, null, compliantHTML, compliantOptions, and Unsafe.
ShadowRoot's prependHTMLUnsafe(html,
options) method steps are:
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".
Filter and pre-insert HTML given this, this's first child, compliantHTML, compliantOptions, and Unsafe.
NonDocumentTypeChildNode's beforeHTMLUnsafe(html,
options) method steps are:
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".
Let parent be the parent for HTML insertion given this.
If parent is null, then return.
Filter and pre-insert HTML given parent, this, compliantHTML, compliantOptions, and Unsafe.
NonDocumentTypeChildNode's afterHTMLUnsafe(html,
options) method steps are:
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".
Let parent be the parent for HTML insertion given this.
If parent is null, then return.
Filter and pre-insert HTML given parent, this's next sibling, compliantHTML, compliantOptions, and Unsafe.
NonDocumentTypeChildNode's replaceWithHTMLUnsafe(html,
options) method steps are:
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".
Let parent be the parent for HTML insertion given this.
If parent is null, then return.
Filter and replace with HTML given parent, this, compliantHTML, compliantOptions, and Unsafe.
The static parseHTML(html,
options) method steps are:
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.
Set document's allow declarative shadow roots to true.
Let sanitizerConfig be the result of getting a sanitizer config from options given options and true.
Assert: sanitizerConfig is non-null.
The sanitizer member of
SetHTMLOptions defaults to "default".
Parse HTML from a string given document, html, and sanitizerConfig.
Return document.
The static parseHTMLUnsafe(html, options)
method steps are:
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".
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.
Set document's allow declarative shadow roots to true.
Let sanitizerConfig be the result of getting a sanitizer config from options given compliantOptions and false.
Parse HTML from a string given document, compliantHTML, and sanitizerConfig.
Return document.
The HTML streaming methods (e.g. streamHTML())
allow authors to insert chunks of HTML asynchronously using a WritableStream. As
chunks are written to the stream, the HTML parser incrementally processes the input
and inserts the resulting DOM nodes into the target node.
Unlike synchronous methods such as setHTML(),
streaming methods can parse and execute scripts incrementally when an Unsafe method (e.g. streamHTMLUnsafe()) is used and the runScripts option is set to true. Scripts are
executed as their end tags are parsed (or when the stream closes, for defer and parser-inserted "module"
scripts), similar to main document parsing, except that streamed style sheets do not block
streamed scripts, and document.write() targets the live
document rather than the stream. Because the tree is constructed incrementally, scripts can
observe partial markup and DOM elements appended before the stream is closed.
The promise returned by writing a chunk to the stream is settled once the chunk has been parsed
as far as possible. If parsing is blocked on a script that is being fetched, the promise does not
wait for it; subsequent chunks are parsed once that script has been executed. Similarly, the
promise returned by closing the stream does not wait for defer or "module" scripts; they are
executed in subsequent tasks, after the promise settles. If the node before which content is being
inserted is moved or removed while streaming, e.g., by a script, writing a subsequent chunk errors
the stream, and nodes that would have been inserted before it in the meantime are dropped.
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 provides context for the HTML parser. The parsed fragments are sanitized based on options's sanitizer member, and unsafe content is removed. 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's host provides
context for the HTML parser. The parsed fragments are sanitized
based on options's sanitizer
member, and unsafe content is removed.
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 provides context for the HTML parser. The
parsed fragments are sanitized based on options's sanitizer member, and unsafe content is removed. 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's host provides context for the HTML parser. The
parsed fragments are sanitized based on options's sanitizer member, and unsafe content is removed.
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 provides context for the HTML parser. The
parsed fragments are sanitized based on options's sanitizer member, and unsafe content is removed. Throws a
"NotSupportedError" DOMException if element is
an HTML or SVG script element. While streaming, content is inserted before
element's first child (or the template contents's
first child), at the time of calling the method. The stream rejects with a
"HierarchyRequestError" DOMException if that node is no
longer a child of the target.
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's host provides context for the HTML parser. The
parsed fragments are sanitized based on options's sanitizer member, and unsafe content is removed. While streaming, content is
inserted before shadowRoot's first child, at the time of calling the
method. The stream rejects with a "HierarchyRequestError"
DOMException if that node is no longer a child of shadowRoot.
stream = childNode.streamBeforeHTML([options])Returns a WritableStream that, as strings are written to it, parses them
using the HTML parser, and incrementally inserts the result before childNode.
childNode's parent (or, if that parent is a shadow root or template
contents, its host) provides context
for the HTML parser. The parsed fragments are sanitized based on
options's sanitizer member, and
unsafe content is removed. Throws a
"NotSupportedError" DOMException if childNode's
parent is an HTML or SVG script element. Throws a
"HierarchyRequestError" DOMException if
childNode's parent is null, a Document, a
template element, or a DocumentFragment without a host. While streaming, content is inserted before
childNode, at the time of calling the method. The stream rejects with a
"HierarchyRequestError" DOMException if that node is no
longer a child of its parent.
stream = childNode.streamAfterHTML([options])Returns a WritableStream that, as strings are written to it, parses them
using the HTML parser, and incrementally inserts the result after childNode.
childNode's parent (or, if that parent is a shadow root or template
contents, its host) provides context
for the HTML parser. The parsed fragments are sanitized based on
options's sanitizer member, and
unsafe content is removed. Throws a
"NotSupportedError" DOMException if childNode's
parent is an HTML or SVG script element. Throws a
"HierarchyRequestError" DOMException if
childNode's parent is null, a Document, a
template element, or a DocumentFragment without a host. While streaming, content is inserted before
childNode's next sibling (or after the last child of
childNode's parent if it was the last child), at the time of calling the
method. The stream rejects with a "HierarchyRequestError"
DOMException if that next sibling is no longer a child of childNode's
parent.
stream = childNode.streamReplaceWithHTML([options])Removes childNode, 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. childNode's parent (or, if that parent is a shadow root or template
contents, its host) provides context
for the HTML parser. The parsed fragments are sanitized based on
options's sanitizer member, and
unsafe content is removed. Throws a
"NotSupportedError" DOMException if childNode's
parent is an HTML or SVG script element. Throws a
"HierarchyRequestError" DOMException if
childNode's parent is null, a Document, a
template element, or a DocumentFragment without a host. While streaming, content is inserted before
childNode's next sibling (or after the last child of
childNode's former parent if it was the last child), at the time of
calling the method. The stream rejects with a "HierarchyRequestError"
DOMException if that next sibling is no longer a child of childNode'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 provides context for the HTML parser. If options is a
SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragments before they are
inserted into element. If options's runScripts is true, scripts written to the
stream will be executed as they are parsed (or when the stream closes, for defer and parser-inserted "module"
scripts), unless altered by a Trusted Types default policy. Throws a
"NotSupportedError" DOMException if element is
an HTML or SVG script element. Throws a TypeError if Trusted Types are
enforced and options is not a TrustedHTMLParserOptions object, unless a default
policy's createParserOptions returns a value other than 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's host provides
context for the HTML parser. If options is a SetHTMLUnsafeOptions
dictionary containing a sanitizer member
or a TrustedHTMLParserOptions object with a
non-null sanitizer configuration, it is used to sanitize the parsed fragments before
they are inserted into shadowRoot. If options's runScripts is true, scripts written to the
stream will be executed as they are parsed (or when the stream closes, for defer and parser-inserted "module"
scripts), unless altered by a Trusted Types default policy. Throws a TypeError if
Trusted Types are enforced and options is not a TrustedHTMLParserOptions object, unless a default
policy's createParserOptions returns a value other than null or undefined.
Exceptions thrown by createParserOptions are rethrown.
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 provides context for the HTML parser. If
options is a SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragments before they are
inserted into element. If options's runScripts is true, scripts written to the
stream will be executed as they are parsed (or when the stream closes, for defer and parser-inserted "module"
scripts), unless altered by a Trusted Types default policy. Throws a
"NotSupportedError" DOMException if element is
an HTML or SVG script element. Throws a TypeError if Trusted Types are
enforced and options is not a TrustedHTMLParserOptions object, unless a default
policy's createParserOptions returns a value other than null or undefined.
Exceptions thrown by createParserOptions are rethrown.
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's host provides context for the HTML parser. If
options is a SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragments before they are
inserted into shadowRoot. If options's runScripts is true, scripts written to the
stream will be executed as they are parsed (or when the stream closes, for defer and parser-inserted "module"
scripts), unless altered by a Trusted Types default policy. Throws a TypeError if
Trusted Types are enforced and options is not a TrustedHTMLParserOptions object, unless a default
policy's createParserOptions returns a value other than null or undefined.
Exceptions thrown by createParserOptions are rethrown.
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 provides context for the HTML parser. If
options is a SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragments before they are
inserted into element. If options's runScripts is true, scripts written to the
stream will be executed as they are parsed (or when the stream closes, for defer and parser-inserted "module"
scripts), unless altered by a Trusted Types default policy. Throws a
"NotSupportedError" DOMException if element is
an HTML or SVG script element. Throws a TypeError if Trusted Types are
enforced and options is not a TrustedHTMLParserOptions object, unless a default
policy's createParserOptions returns a value other than null or undefined.
Exceptions thrown by createParserOptions are rethrown. While streaming,
content is inserted before element's first child (or the template
contents's first child), at the time of calling the method. The stream
rejects with a "HierarchyRequestError" DOMException if
that node is no longer a child of the target.
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's host provides context for the HTML parser. If
options is a SetHTMLUnsafeOptions dictionary containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragments before they are
inserted into shadowRoot. If options's runScripts is true, scripts written to the
stream will be executed as they are parsed (or when the stream closes, for defer and parser-inserted "module"
scripts), unless altered by a Trusted Types default policy. Throws a TypeError if
Trusted Types are enforced and options is not a TrustedHTMLParserOptions object, unless a default
policy's createParserOptions returns a value other than null or undefined.
Exceptions thrown by createParserOptions are rethrown. While streaming,
content is inserted before shadowRoot's first child, at the time of
calling the method. The stream rejects with a "HierarchyRequestError"
DOMException if that node is no longer a child of shadowRoot.
stream = childNode.streamBeforeHTMLUnsafe([options])Returns a WritableStream that, as strings are written to it, parses them
using the HTML parser, and incrementally inserts the result before childNode.
childNode's parent (or, if that parent is a shadow root or template
contents, its host) provides context
for the HTML parser. If options is a SetHTMLUnsafeOptions dictionary
containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragments before they are
inserted into the node tree. If options's runScripts is true, scripts written to the
stream will be executed as they are parsed (or when the stream closes, for defer and parser-inserted "module"
scripts), unless altered by a Trusted Types default policy. Throws a
"NotSupportedError" DOMException if childNode's
parent is an HTML or SVG script element. Throws a
"HierarchyRequestError" DOMException if
childNode's parent is null, a Document, a
template element, or a DocumentFragment without a host. Throws a TypeError if Trusted
Types are enforced and options is not a TrustedHTMLParserOptions object, unless a default
policy's createParserOptions returns a value other than null or undefined.
Exceptions thrown by createParserOptions are rethrown. While streaming,
content is inserted before childNode, at the time of calling the method. The stream
rejects with a "HierarchyRequestError" DOMException if
that node is no longer a child of its parent.
stream = childNode.streamAfterHTMLUnsafe([options])Returns a WritableStream that, as strings are written to it, parses them
using the HTML parser, and incrementally inserts the result after childNode.
childNode's parent (or, if that parent is a shadow root or template
contents, its host) provides context
for the HTML parser. If options is a SetHTMLUnsafeOptions dictionary
containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragments before they are
inserted into the node tree. If options's runScripts is true, scripts written to the
stream will be executed as they are parsed (or when the stream closes, for defer and parser-inserted "module"
scripts), unless altered by a Trusted Types default policy. Throws a
"NotSupportedError" DOMException if childNode's
parent is an HTML or SVG script element. Throws a
"HierarchyRequestError" DOMException if
childNode's parent is null, a Document, a
template element, or a DocumentFragment without a host. Throws a TypeError if Trusted
Types are enforced and options is not a TrustedHTMLParserOptions object, unless a default
policy's createParserOptions returns a value other than null or undefined.
Exceptions thrown by createParserOptions are rethrown. While streaming,
content is inserted before childNode's next sibling (or after the last
child of childNode's parent if it was the last child), at the time of
calling the method. The stream rejects with a "HierarchyRequestError"
DOMException if that next sibling is no longer a child of childNode's
parent.
stream = childNode.streamReplaceWithHTMLUnsafe([options])Removes childNode, 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. childNode's parent (or, if that parent is a shadow root or template
contents, its host) provides context
for the HTML parser. If options is a SetHTMLUnsafeOptions dictionary
containing a sanitizer member or a TrustedHTMLParserOptions object with a non-null
sanitizer configuration, it is used to sanitize the parsed fragments before they are
inserted into the node tree. If options's runScripts is true, scripts written to the
stream will be executed as they are parsed (or when the stream closes, for defer and parser-inserted "module"
scripts), unless altered by a Trusted Types default policy. Throws a
"NotSupportedError" DOMException if childNode's
parent is an HTML or SVG script element. Throws a
"HierarchyRequestError" DOMException if
childNode's parent is null, a Document, a
template element, or a DocumentFragment without a host. Throws a TypeError if Trusted
Types are enforced and options is not a TrustedHTMLParserOptions object, unless a default
policy's createParserOptions returns a value other than null or undefined.
Exceptions thrown by createParserOptions are rethrown. While streaming,
content is inserted before childNode's next sibling (or after the last
child of childNode's former parent if it was the last child), at the time
of calling the method. The stream rejects with a
"HierarchyRequestError" DOMException if that next sibling
is no longer a child of childNode's former parent.
Element's streamHTML(options) method steps are:
Let target be the target for HTML insertion given this.
Let stream be the result of running stream HTML given target, null, options, true, and this's relevant realm.
Replace all with null within target.
Return stream.
Element's streamAppendHTML(options) method
steps are:
Let target be the target for HTML insertion given this.
Return the result of running stream HTML given target, null, options, true, and this's relevant realm.
Element's streamPrependHTML(options) method
steps are:
Let target be the target for HTML insertion given this.
Return the result of running stream HTML given target, target's first child, options, true, and this's relevant realm.
Element's streamHTMLUnsafe(options) method
steps are:
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".
Let target be the target for HTML insertion given this.
Let stream be the result of running stream HTML given target, null, compliantOptions, false, and this's relevant realm.
Replace all with null within target.
Return stream.
Element's streamAppendHTMLUnsafe(options)
method steps are:
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".
Let target be the target for HTML insertion given this.
Return the result of running stream HTML given target, null, compliantOptions, false, and this's relevant realm.
Element's streamPrependHTMLUnsafe(options)
method steps are:
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".
Let target be the target for HTML insertion given this.
Return the result of running stream HTML given target, target's first child, compliantOptions, false, and this's relevant realm.
ShadowRoot's streamHTML(options) method steps
are:
Let stream be the result of running stream HTML given this, null, options, true, and this's relevant realm.
Replace all with null within this.
Return stream.
ShadowRoot's streamAppendHTML(options) method
steps are to return the result of running stream HTML given this, null,
options, true, 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, true, and this's
relevant realm.
ShadowRoot's streamHTMLUnsafe(options) method
steps are:
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".
Let stream be the result of running stream HTML given this, null, compliantOptions, false, and this's relevant realm.
Replace all with null within this.
Return stream.
ShadowRoot's streamAppendHTMLUnsafe(options)
method steps are:
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".
Return the result of running stream HTML given this, null, compliantOptions, false, and this's relevant realm.
ShadowRoot's streamPrependHTMLUnsafe(options)
method steps are:
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".
Return the result of running stream HTML given this, this's first child, compliantOptions, false, and this's relevant realm.
NonDocumentTypeChildNode's streamBeforeHTML(options)
method steps are:
Let parent be the parent for HTML streaming given this.
Return the result of running stream HTML given parent, this, options, true, and this's relevant realm.
NonDocumentTypeChildNode's streamAfterHTML(options)
method steps are:
Let parent be the parent for HTML streaming given this.
Return the result of running stream HTML given parent, this's next sibling, options, true, and this's relevant realm.
NonDocumentTypeChildNode's streamReplaceWithHTML(options)
method steps are:
Let parent be the parent for HTML streaming given this.
Let stream be the result of running stream HTML given parent, this's next sibling, options, true, and this's relevant realm.
Return stream.
NonDocumentTypeChildNode's streamBeforeHTMLUnsafe(options)
method steps are:
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".
Let parent be the parent for HTML streaming given this.
Return the result of running stream HTML given parent, this, compliantOptions, false, and this's relevant realm.
NonDocumentTypeChildNode's streamAfterHTMLUnsafe(options)
method steps are:
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".
Let parent be the parent for HTML streaming given this.
Return the result of running stream HTML given parent, this's next sibling, compliantOptions, false, and this's relevant realm.
NonDocumentTypeChildNode's streamReplaceWithHTMLUnsafe(options)
method steps are:
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".
Let parent be the parent for HTML streaming given this.
Let stream be the result of running stream HTML given parent, this's next sibling, compliantOptions, false, and this's relevant realm.
Return stream.
To get the parent for HTML streaming, given a Node node:
Let parent be the parent for HTML insertion given node.
If parent is null, then throw a
"HierarchyRequestError" DOMException.
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
boolean safe, and a realm realm:
Let context be the parser context element given target.
Assert: context is non-null.
If context's local name is
"script" and context's namespace is the HTML namespace or the
SVG namespace, then throw a "NotSupportedError"
DOMException.
This is done regardless of safe. Streaming into a script
element would cause its children changed steps to prepare it with only part of its source text.
Let sanitizerConfig be the result of getting a sanitizer config from options given options and safe.
Let runScripts be false.
If safe is false:
If options is a TrustedHTMLParserOptions, then set
runScripts to options's runScripts.
Otherwise, set runScripts to options["runScripts"] with default false.
Let parser be the result of initializing an HTML fragment parser given document, target, (target, referenceChild), runScripts, true, and sanitizerConfig. parser is a script-created parser.
This ensures that parser does not reach the end of its input
stream when it has consumed a chunk, but only when it consumes the explicit "EOF"
character appended when the returned stream is closed. Since document is not
exposed to script, document.close() cannot close
parser.
Let stream be a new WritableStream created in
realm.
Let writeAlgorithm be the following steps given chunk:
Let chunkString be the result of converting chunk to a DOMString. If this throws an exception, then abort parser and return a promise rejected with that exception,
created in realm.
If referenceChild is non-null and referenceChild's parent is not target:
Abort parser.
Return a promise rejected with a new "HierarchyRequestError"
DOMException, created in realm.
This is only checked when a chunk is written. If referenceChild is moved or removed while parser is running, e.g., by a custom element reaction or by a script that parser was blocked on, then nodes that would have been inserted before it are dropped, and parsing continues. Closing the stream is not affected.
Append chunkString to the end of parser's input stream, and run a fragment parser given parser. The encoding confidence is irrelevant.
Return a promise resolved with undefined, created in realm.
The returned promise does not wait for a pending parsing-blocking script to be executed. While parser is blocked, subsequent input accumulates in its input stream, and is parsed after the script has been executed.
Let closeAlgorithm be the following steps:
Append an explicit "EOF" character to the end of parser's input stream, and run a fragment parser given parser.
Return a promise resolved with undefined, created in realm.
The returned promise does not wait for a pending parsing-blocking
script, or for deferred or "module" scripts, to be executed. Once it is settled, stream is
closed and can no longer be aborted, so pending scripts are still executed.
Let abortAlgorithm be the following steps: if parser has not been aborted, then abort parser.
This only runs once any write in progress has completed. For example, if a
script in the chunk being written aborts stream, the rest of that chunk is still
parsed. Aborting the parser would fire a readystatechange event on the temporary inert document,
which is not observable.
Set up stream with writeAlgorithm, closeAlgorithm, and abortAlgorithm.
Return stream.
html = element.getHTML({ serializableShadowRoots, shadowRoots })Returns the result of serializing element to HTML. Shadow roots within element are serialized according to the provided options:
If serializableShadowRoots is true, then all shadow roots marked as serializable are serialized.
If the shadowRoots array is provided, then all shadow roots specified in the array are serialized, regardless of whether or not they are marked as serializable.
If neither option is provided, then no shadow roots are serialized.
html = shadowRoot.getHTML({ serializableShadowRoots, shadowRoots })Returns the result of serializing shadowRoot to HTML, using its shadow host as the context element. Shadow roots within shadowRoot are serialized according to the provided options, as above.
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"].
innerHTML propertyThe innerHTML property has a number of outstanding issues
in the DOM Parsing and Serialization issue
tracker, documenting various problems with its specification.
element.innerHTMLReturns a fragment of HTML or XML that represents the element's contents.
In the case of an XML document, throws an "InvalidStateError"
DOMException if the element cannot be serialized to XML.
element.innerHTML = valueReplaces the contents of the element with nodes parsed from the given string.
In the case of an XML document, throws a "SyntaxError"
DOMException if the given string is not well-formed.
Setting innerHTML on a
template element will replace all the nodes in its template contents
rather than its children.
shadowRoot.innerHTMLReturns a fragment of HTML that represents the shadow roots's contents.
shadowRoot.innerHTML = valueReplaces the contents of the shadow root with nodes parsed from the given string.
By default, these properties' setters perform no sanitization to remove
potentially-dangerous elements and attributes like script or event handler
content attributes.
The fragment serializing algorithm steps, given an Element,
Document, or DocumentFragment node and a boolean require
well-formed, are:
Let context document be node's node document.
If context document is an HTML document, then return the result of HTML fragment serialization algorithm with node, false, and « ».
Return the XML serialization of node given require well-formed.
A fragment parser mode is one of the following:
Unsafe elements and attributes are removed, while the allow declarative shadow roots flag 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 declarative shadow roots are allowed (the allow declarative shadow roots flag 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, while the allow declarative shadow roots flag is false. In XML documents, the XML parser is used.
To get the target for HTML insertion, given an Element or
DocumentFragment target:
If target is a template element, then return target's
template contents.
Return target.
When target is a template element, the HTML insertion
methods manipulate its template contents rather than its children.
To get the parent for HTML insertion, given a Node node:
If node's parent is a template element, then throw a
"HierarchyRequestError" DOMException.
If node's parent is null, an Element, or a
DocumentFragment with a non-null host, then return node's
parent.
Throw a "HierarchyRequestError"
DOMException.
This diverges from the DOM insertion methods (such as before()), which do not treat these parents as invalid. This
is because the HTML insertion methods require an Element context for the fragment
parser, which a Document or hostless DocumentFragment cannot provide.
Furthermore, inserting adjacent to children of a template element is disallowed
because the HTML insertion methods target the template element's template
contents rather than its children.
While legacy methods such as outerHTML
and insertAdjacentHTML() throw a
"NoModificationAllowedError" DOMException when the parent
is a Document, the HTML insertion 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:
Let fragment be the result of invoking the fragment parsing algorithm steps given target, html, options, and mode.
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:
Let fragment be the result of invoking the fragment parsing algorithm steps given parent, html, options, and mode.
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:
Let fragment be the result of invoking the fragment parsing algorithm steps given parent, html, options, and mode.
If fragment is non-null, then replace node with fragment within parent.
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:
If mode is Safe:
Let context be the parser context element given target.
Assert: context is non-null.
If all of the following are true:
context's local name is
"script"; and
context's namespace is the HTML namespace or the SVG namespace,
then return null.
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.
Let safe be true if mode is Safe; otherwise false.
Let sanitizerConfig be the result of getting a sanitizer config from options given options and safe.
Let runScripts be options's runScripts if options is a
TrustedHTMLParserOptions; otherwise
options["runScripts"] with default false.
Let allowDeclarativeShadowRoots be false if mode is Legacy; otherwise true.
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:
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.
Let target be the target for HTML insertion given this.
Filter and set HTML given target, compliantString, compliantOptions, and Legacy.
ShadowRoot's innerHTML setter steps
are:
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.
Filter and set HTML given this, compliantString, compliantOptions, and Legacy.
outerHTML propertyThe outerHTML property has a number of outstanding issues
in the DOM Parsing and Serialization issue
tracker, documenting various problems with its specification.
element.outerHTMLReturns a fragment of HTML or XML that represents the element and its contents.
In the case of an XML document, throws an "InvalidStateError"
DOMException if the element cannot be serialized to XML.
element.outerHTML = valueReplaces the element with nodes parsed from the given string.
In the case of an XML document, throws a "SyntaxError"
DOMException if the given string is not well-formed.
Throws a "NoModificationAllowedError" DOMException if
the parent of the element is a Document.
By default, this property's setter performs no sanitization to remove
potentially-dangerous elements and attributes like script or event handler
content attributes.
Element's outerHTML getter steps are:
Let element be a fictional node whose only child is this.
Return the result of running fragment serializing algorithm steps with element and true.
Element's outerHTML setter steps
are:
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.
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.
If parent is a Document, throw a
"NoModificationAllowedError" DOMException.
If parent is a DocumentFragment, set parent to the
result of creating an element given this's
node document, "body", and the HTML
namespace.
Let fragment be the result of invoking the fragment parsing algorithm steps given parent, compliantString, compliantOptions, and Legacy.
insertAdjacentHTML() methodThe insertAdjacentHTML()
method has a number of outstanding issues in the DOM Parsing and Serialization issue tracker, documenting various problems
with its specification.
element.insertAdjacentHTML(position, string)Parses string as HTML or XML and inserts the resulting nodes into the tree in the position given by the position argument, as follows:
beforebegin"afterbegin"beforeend"afterend"Throws a "SyntaxError" DOMException if the arguments
have invalid values (e.g., in the case of an XML document,
if the given string is not well-formed).
Throws a "NoModificationAllowedError" DOMException
if the given position isn't possible (e.g. inserting elements after the root element of a
Document).
By default, this method performs no sanitization to remove
potentially-dangerous elements and attributes like script or event handler
content attributes.
Element's insertAdjacentHTML(position,
string) method steps are:
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.
Let context be null.
Use the first matching item from this list:
beforebegin"afterend"If context is null or a Document, throw a
"NoModificationAllowedError" DOMException.
afterbegin"beforeend"Throw a "SyntaxError" DOMException.
If context is not an Element or all of the following are true:
context's node document is an HTML document;
context's local name is
"html"; and
context's namespace is the HTML namespace,
then set context to the result of creating an
element given this's node document, "body", and the HTML namespace.
Let fragment be the result of invoking the fragment parsing algorithm steps given context, compliantString, compliantOptions, and Legacy.
beforebegin"afterbegin"Insert fragment into this before its first child.
beforeend"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.
createContextualFragment()
methodThe createContextualFragment() method has a number
of outstanding issues in the DOM Parsing and Serialization issue tracker, documenting various problems
with its specification.
docFragment = range.createContextualFragment(string)Returns a DocumentFragment created from the markup string string using
range's start node as the context in
which fragment is parsed.
By default, this method performs no sanitization to remove
potentially-dangerous elements and attributes like script or event handler
content attributes.
partial interface Range {
[CEReactions, NewObject] DocumentFragment createContextualFragment((TrustedHTML or DOMString) string);
};
Range's createContextualFragment(string)
method steps are:
Let node be this's start node.
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.
Let element be null.
If node implements Element, set element
to node.
Otherwise, if node implements Text or
Comment, set element to node's parent
element.
If element is null or all of the following are true:
element's node document is an HTML document;
element's local name is
"html"; and
element's namespace is the HTML namespace,
then set element to the result of creating an
element given node's node document, "body", and the HTML namespace.
Return the result of invoking the fragment parsing algorithm steps given element, compliantString, compliantOptions, and Legacy.
XMLSerializer interfaceThe XMLSerializer interface has a number of outstanding issues in the
DOM Parsing and Serialization issue tracker, documenting various problems
with its specification. The remainder of DOM Parsing and Serialization will be
gradually upstreamed to this specification.
xmlSerializer = new XMLSerializer()Constructs a new XMLSerializer object.
string = xmlSerializer.serializeToString(root)Returns the result of serializing root to XML.
Throws an "InvalidStateError" DOMException if
root cannot be serialized to XML.
The design of XMLSerializer, as a class that needs to be constructed
and then have its serializeToString()
method called, is an unfortunate historical artifact. If we were designing this functionality
today it would be a standalone function.
[Exposed=Window]
interface XMLSerializer {
constructor();
DOMString serializeToString(Node root);
};
The new XMLSerializer()
constructor steps are to do nothing.
The serializeToString(root)
method steps are:
Return the XML serialization of root given false.
This section is non-normative.
Web applications often need to process untrusted HTML strings, such as when rendering user-generated content or using client-side templates. Safely inserting these strings into the DOM requires careful sanitization to prevent DOM-based cross-site scripting (XSS) attacks.
HTML sanitization provides a native mechanism for safely parsing and sanitizing HTML strings. By using the user agent's own HTML parser, they ensure the sanitized output accurately reflects how the browser will render the content, preventing script execution and mitigating advanced attacks such as script gadgets.
These APIs offer functionality to parse a string containing HTML into a DOM tree, and sanitize the resulting DOM as it is being parsed. The methods come in two main flavors: "safe" and "unsafe".
The "safe" methods will not generate any markup that executes script. That is, they are intended to be safe from XSS. The "unsafe" methods will parse and filter based on the provided configuration, but do not have the same safety guarantees by default.
Sanitizer interface[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()Returns a copy of the sanitizer's configuration.
sanitizer.allowElement(element)Ensures that the sanitizer configuration allows the specified element.
sanitizer.removeElement(element)Ensures that the sanitizer configuration blocks the specified element.
sanitizer.replaceElementWithChildren(element)Configures the sanitizer to remove the specified element but keep its child nodes.
sanitizer.allowAttribute(attribute)Configures the sanitizer to allow the specified attribute globally.
sanitizer.removeAttribute(attribute)Configures the sanitizer to block the specified attribute globally.
sanitizer.allowProcessingInstruction(pi)Configures the sanitizer to allow the specified processing instruction.
sanitizer.removeProcessingInstruction(pi)Configures the sanitizer to block the specified processing instruction.
sanitizer.setComments(allow)Sets whether the sanitizer preserves comments.
sanitizer.setDataAttributes(allow)Sets whether the sanitizer preserves custom data attributes (e.g., data-*).
sanitizer.setJavascriptURLs(allow)Sets whether the sanitizer preserves attributes containing javascript: URLs.
sanitizer.removeUnsafe()Modifies the configuration to automatically remove elements and attributes that are considered unsafe.
A Sanitizer object has an associated configuration, which is a SanitizerConfig.
The new
Sanitizer(configuration) constructor steps are:
If configuration is a SanitizerPresets string:
Set configuration to the built-in safe default configuration.
To configure a
Sanitizer sanitizer, given a dictionary configuration and a
boolean permissiveDefaults:
Let freshConfiguration be a clone of configuration.
Canonicalize the configuration freshConfiguration with permissiveDefaults.
Set sanitizer's configuration to freshConfiguration.
To canonicalize the configuration SanitizerConfig configuration with a boolean permissiveDefaults:
If neither configuration["elements"] nor configuration["removeElements"] exists, then set configuration["removeElements"] to an empty list.
If neither configuration["attributes"] nor configuration["removeAttributes"] exists, then set configuration["removeAttributes"] to an empty
list.
If neither configuration["processingInstructions"] nor
configuration["removeProcessingInstructions"]
exists:
If permissiveDefaults is true, then set configuration["removeProcessingInstructions"]
to an empty list.
Otherwise, set configuration["processingInstructions"] to an empty
list.
If configuration["elements"]
exists:
Let newElements be « ».
For each element of
configuration["elements"], append the result of canonicalizing element to newElements.
Set configuration["elements"] to newElements.
If configuration["removeElements"] exists, then set configuration["removeElements"] to the result of canonicalizing
configuration["removeElements"].
If configuration["attributes"] exists, then set configuration["attributes"] to the result of canonicalizing configuration["attributes"].
If configuration["removeAttributes"] exists, then set configuration["removeAttributes"] to the result of canonicalizing configuration["removeAttributes"].
If configuration["replaceWithChildrenElements"]
exists, then set configuration["replaceWithChildrenElements"] to
the result of canonicalizing
configuration["replaceWithChildrenElements"].
If configuration["processingInstructions"] exists, then set configuration["processingInstructions"] to the result
of canonicalizing
configuration["processingInstructions"].
If configuration["removeProcessingInstructions"]
exists, then set configuration["removeProcessingInstructions"]
to the result of canonicalizing
configuration["removeProcessingInstructions"].
If configuration["comments"]
does not exist, then set it to
permissiveDefaults.
If configuration["attributes"] exists and configuration["dataAttributes"] does not exist, then set it to permissiveDefaults.
If configuration["javascriptURLs"] does not exist, then set it to permissiveDefaults.
To canonicalize a sanitizer list list:
Let newList be « ».
For each item in list, append the result of canonicalizing item to newList.
Return newList.
To canonicalize a processing instruction list list:
Let newList be « ».
For each item in list, append the result of canonicalizing item to newList.
Return newList.
To canonicalize a processing instruction given a SanitizerPI
pi:
To canonicalize a sanitizer name given a DOMString or dictionary name, and a default namespace
defaultNamespace (default null):
To canonicalize a sanitizer element given a SanitizerElement
element:
Return the result of canonicalizing element with the HTML namespace as the default namespace.
To canonicalize a sanitizer element list list:
Let newList be « ».
For each item in list, append the result of canonicalizing item to newList.
Return newList.
To find the canonicalized intersection of lists A and B:
Let setA be « ».
Let setB be « ».
For each entry of A, append the result of canonicalizing entry to setA.
For each entry of B, append the result of canonicalizing entry to setB.
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.
Let config be this's configuration.
For each element of config["elements"]:
If element["attributes"] exists, then set element["attributes"] to the
result of sorting element["attributes"], with
compare sanitizer items.
If element["removeAttributes"]
exists, then set element["removeAttributes"]
to the result of sorting element["removeAttributes"],
with compare sanitizer items.
Set config["elements"] to
the result of sorting config["elements"], with compare sanitizer
items.
Otherwise:
Set config["removeElements"] to the result of sorting config["removeElements"], with compare
sanitizer items.
If config["replaceWithChildrenElements"]
exists, then set config["replaceWithChildrenElements"] to
the result of sorting config["replaceWithChildrenElements"],
with compare sanitizer items.
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"].
Otherwise:
Set config["removeProcessingInstructions"]
to the result of sorting config["removeProcessingInstructions"],
with piA["target"]
being code unit less than piB["target"].
If config["attributes"]
exists, then set config["attributes"] to the result of sorting config["attributes"] given compare sanitizer
items.
Otherwise:
Set config["removeAttributes"] to the result of sorting config["removeAttributes"] given compare
sanitizer items.
Return config.
The allowElement(element) method steps
are:
Let configuration be this's configuration.
Set element to the result of canonicalizing element.
If configuration["elements"]
exists:
Let modified be the result of removing
element from configuration["replaceWithChildrenElements"].
If configuration["attributes"] exists:
If element["attributes"] exists:
Set element["attributes"] to the
result of creating a set from element["attributes"].
Set element["attributes"] to the
difference of element["attributes"] and
configuration["attributes"].
If configuration["dataAttributes"] is true, then remove all items item from element["attributes"] where
item is a custom data attribute.
If element["removeAttributes"]
exists:
Set element["removeAttributes"]
to the result of creating a set from
element["removeAttributes"].
Set element["removeAttributes"]
to the intersection of
element["removeAttributes"]
and configuration["attributes"].
Otherwise:
If element["attributes"] exists:
Set element["attributes"] to the
result of creating a set from element["attributes"].
Set element["attributes"] to the
difference of element["attributes"] and
element["removeAttributes"]
with default « ».
Remove element["removeAttributes"].
Set element["attributes"] to the
difference of element["attributes"] and
configuration["removeAttributes"].
If element["removeAttributes"]
exists:
Set element["removeAttributes"]
to the result of creating a set from
element["removeAttributes"].
Set element["removeAttributes"]
to the difference of element["removeAttributes"]
and configuration["removeAttributes"].
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.
If element is equal to currentElement, then return modified.
Return true.
Otherwise:
If element["attributes"] exists or element["removeAttributes"]
with default « » is not empty, then return
false.
Let modified be the result of removing
element from configuration["replaceWithChildrenElements"].
If configuration["removeElements"] does not contain element, then return modified.
Remove element from
configuration["removeElements"].
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:
Let configuration be this's configuration.
Set element to the result of canonicalizing element.
If the built-in non-replaceable elements list contains element, then return false.
Let modified be the result of removing
element from configuration["elements"].
If removing element from
configuration["removeElements"] is true, then set
modified to true.
If configuration["replaceWithChildrenElements"]
does not contain element:
Append element to
configuration["replaceWithChildrenElements"].
Return true.
Return modified.
The allowAttribute(attribute) method
steps are:
Let configuration be this's configuration.
Set attribute to the result of canonicalizing attribute.
If configuration["attributes"] exists:
If configuration["dataAttributes"] is true and
attribute is a custom data attribute, then return false.
If configuration["attributes"] contains attribute, then return false.
If configuration["elements"]
exists:
For each element in
configuration["elements"]:
If element["attributes"] with default « » contains attribute, then remove attribute from element["attributes"].
Append attribute to
configuration["attributes"].
Return true.
Otherwise:
If configuration["removeAttributes"] does not contain attribute, then return false.
Remove attribute from
configuration["removeAttributes"].
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:
The setDataAttributes(allow) method
steps are:
Let configuration be this's configuration.
If configuration["attributes"] does not exist, then return false.
If configuration["dataAttributes"] exists and is equal to allow, then return false.
If allow is true:
If configuration["elements"]
exists:
For each element of
configuration["elements"]:
If element["attributes"] exists, then remove all items
item from element["attributes"] where
item is a custom data attribute.
Remove all items item from
configuration["attributes"]
where item is a custom data attribute.
Set configuration["dataAttributes"] to allow.
Return true.
The setJavascriptURLs(allow) method
steps are:
Let configuration be this's configuration.
If configuration["javascriptURLs"] is allow, then
return false.
Set configuration["javascriptURLs"] to allow.
Return true.
The allowProcessingInstruction(pi)
method steps are:
Let configuration be this's configuration.
Set pi to the result of canonicalizing pi.
If configuration["processingInstructions"] exists:
If configuration["processingInstructions"] contains pi, then return false.
Append pi to
configuration["processingInstructions"].
Return true.
Otherwise:
If configuration["removeProcessingInstructions"]
contains pi:
Remove pi from
configuration["removeProcessingInstructions"].
Return true.
Return false.
The removeProcessingInstruction(pi)
method steps are:
Let configuration be this's configuration.
Set pi to the result of canonicalizing pi.
If configuration["processingInstructions"] exists:
If configuration["processingInstructions"] contains pi:
Remove pi from
configuration["processingInstructions"].
Return true.
Return false.
Otherwise:
If configuration["removeProcessingInstructions"]
contains pi, then return false.
Append pi to
configuration["removeProcessingInstructions"].
Return true.
The removeUnsafe() method steps are to return the
result of removing unsafe from this's
configuration.
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, and
SanitizerProcessingInstruction dictionaries are considered equal when all of their
members are equal.
Equality should be defined in the infra spec instead. See issue #664.
This section is non-normative.
Configurations can and ought to be modified by developers to suit their purposes. Options are
to write a new SanitizerConfig dictionary from scratch, to modify an existing
Sanitizer's configuration by using the modifier methods, or to get() an existing Sanitizer's
configuration as a dictionary and modify the dictionary and then create a new
Sanitizer with it.
An empty configuration allows everything (when called with the "unsafe" methods like setHTMLUnsafe()). A configuration "default" contains a
built-in safe default configuration. Note that "safe" and "unsafe" sanitizer methods
have different defaults.
Not all configuration dictionaries are valid. A valid configuration avoids redundancy (like specifying the same element to be allowed twice) and contradictions (like specifying an element to be both removed and allowed.)
Several conditions need to hold for a configuration to be valid:
Mixing global allow- and remove-lists:
elements or removeElements can exist, but not both. If
both are missing, this is equivalent to removeElements being an empty list.
attributes or removeAttributes can exist, but not both.
If both are missing, this is equivalent to removeAttributes being an empty
list.
dataAttributes is conceptually
an extension of the attributes allow-list.
The dataAttributes member is only
allowed when an attributes list is
used.
Duplicate entries between different global lists:
There are no duplicate entries (i.e., no same elements) between elements, removeElements, or replaceWithChildrenElements.
There are no duplicate entries (i.e., no same attributes) between attributes or removeAttributes.
Mixing local allow- and remove-lists on the same element:
When an attributes list exists,
both, either or none of the attributes and removeAttributes
lists are allowed on the same element.
When a removeAttributes list
exists, either or none of the attributes and removeAttributes
lists are allowed on the same element, but not both.
Duplicate entries on the same element:
There are no duplicate entries between attributes and removeAttributes
on the same element.
No element from the built-in non-replaceable elements list appears in replaceWithChildrenElements,
since replacing these elements with their children could lead to re-parsing issues or invalid
node trees.
The elements element allow-list can also
specify allowing or removing attributes for a given element. This is meant to mirror this
standard's structure, which knows both global attributes as well as local attributes
that apply to a specific element. Global and local attributes can be mixed, but note that
ambiguous configurations where a particular attribute would be allowed by one list and forbidden
by another, are generally invalid.
global attributes | global removeAttributes | |
|---|---|---|
local attributes | An attribute is allowed if it matches either list. No duplicates are allowed. | An attribute is only allowed if it's in the local allow list. No duplicate entries between global remove and local allow lists are allowed. Note that the global remove list has no function for this particular element, but can apply to other elements that do not have a local allow list. |
local removeAttributes | An attribute is allowed if it's in the global allow-list, but not in the local remove-list. Local remove has to be a subset of the global allow lists. | An attribute is allowed if it is in neither list. No duplicate entries between global remove and local remove lists are allowed. |
Please note the asymmetry where mostly no duplicates between global and per-element lists are permitted, but in the case of a global allow-list and a per-element remove-list the latter has to be a subset of the former. An excerpt of the table above, only focusing on duplicates, is as follows:
global attributes | global removeAttributes | |
|---|---|---|
local attributes | No duplicates are allowed. | No duplicates are allowed. |
local removeAttributes | Local remove has to be a subset of the global allow lists. | No duplicates are allowed. |
The dataAttributes setting allows
custom data attributes. The rules above easily extends
to custom data attributes if one considers dataAttributes to be an allow-list:
global attributes and dataAttributes set | |
|---|---|
local attributes | All custom data attributes are allowed. No custom data attributes can be listed in any allow-list, as that would mean a duplicate entry. |
local removeAttributes | A custom data attribute is allowed, unless it's listed in the local remove-list. No custom data attribute can be listed in the global allow-list, as that would mean a duplicate entry. |
Putting these rules in words:
Duplicates and interactions between global and local lists:
If a global attributes allow list
exists, then all element's local lists:
If a local attributes allow list
exists, there can be no duplicate entries between these lists.
If a local removeAttributes
remove list exists, then all its entries also need to be listed in the global attributes allow list.
If dataAttributes is true,
then no custom data attributes can be listed in
any of the allow-lists.
If a global removeAttributes
remove list exists:
If a local attributes allow list
exists, there can be no duplicate entries between these lists.
If a local removeAttributes
remove list exists, there can be no duplicate entries between these lists.
Not both a local attributes allow list
and local removeAttributes
remove list exists.
dataAttributes has to be
false.
To get a sanitizer config from options given a SetHTMLOptions,
SetHTMLUnsafeOptions, or ParseHTMLUnsafeOptions dictionary, or a TrustedHTMLParserOptions object options,
and a boolean safe:
Let sanitizerInput be null.
If options is a TrustedHTMLParserOptions:
If options's sanitizer configuration is null:
Assert: safe is false.
Return null.
Set sanitizerInput to options's sanitizer configuration.
Otherwise, if options["sanitizer"] exists,
then set sanitizerInput to options["sanitizer"].
Otherwise, if safe is false, then return null.
Otherwise, set sanitizerInput to "default".
Assert: sanitizerInput is either a Sanitizer
instance, a SanitizerPresets member, or a SanitizerConfig
dictionary.
If sanitizerInput is a string:
Return the built-in safe default configuration.
If sanitizerInput is a Sanitizer, then set
sanitizerInput to sanitizerInput's configuration.
If sanitizerInput is a dictionary:
Let config be sanitizerInput's configuration.
If safe is true, then remove unsafe from config.
Return config.
To determine whether a string value contains a javascript:
URL:
Let url be the result of running the basic URL parser on value.
If url is failure, then return false.
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:
If configuration["processingInstructions"] exists, then return whether configuration["processingInstructions"] contains piTarget.
If configuration["removeProcessingInstructions"]
exists and configuration["removeProcessingInstructions"]
contains piTarget, then return false.
Return true.
A sanitizer action is one of the following:
To determine the sanitizer action for element name given a SanitizerElementNamespace elementName and a SanitizerConfig configuration:
If configuration["replaceWithChildrenElements"]
exists and configuration["replaceWithChildrenElements"]
contains elementName, then return "Replace with children".
Otherwise, if configuration["removeElements"] contains elementName, then return "Remove".
Return "Keep".
To check if a sanitizer config allows an attribute given a SanitizerAttributeNamespace attrName, a string value, a SanitizerElementNamespace elementName, and a SanitizerConfig configuration:
Let elementWithLocalAttributes be «[ ]».
If configuration["elements"]
exists and configuration["elements"] contains elementName, then set elementWithLocalAttributes
to configuration["elements"][elementName].
If elementWithLocalAttributes["removeAttributes"]
exists and elementWithLocalAttributes["removeAttributes"]
contains attrName, then return false.
Otherwise, if configuration["attributes"] exists:
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 attrName["name"] or attrName["namespace"] is not null or
configuration["dataAttributes"] is not true, then return
false.
Otherwise:
If elementWithLocalAttributes["attributes"] exists and elementWithLocalAttributes["attributes"] does not
contain attrName, then return false.
Otherwise, if configuration["removeAttributes"] exists and configuration["removeAttributes"] contains attrName, then return false.
If configuration["javascriptURLs"] is true, then return
true.
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.
If elementName["namespace"] is the MathML
namespace, attrName["name"] is "href",
attrName["namespace"]
is null or the XLink namespace, and value contains a
javascript: URL, then return false.
If the built-in animating URL attributes list contains the pair (elementName, attrName), and
value is "href" or "xlink:href", then
return false.
Return true.
To remove an element element from a SanitizerConfig configuration:
Set element to the result of canonicalizing element.
Let modified be the result of removing
element from configuration["replaceWithChildrenElements"].
Otherwise:
If configuration["removeElements"] contains element, then return modified.
Append element to
configuration["removeElements"].
Return true.
To remove an attribute attribute from a SanitizerConfig configuration:
Set attribute to the result of canonicalizing attribute.
If configuration["attributes"] exists:
Let modified be the result of removing
attribute from configuration["attributes"].
If configuration["elements"]
exists:
For each element of
configuration["elements"]:
If element["attributes"] with default « » contains attribute:
Set modified to true.
Remove attribute from
element["attributes"].
If element["removeAttributes"]
with default « » contains attribute:
Assert: modified is true.
Remove attribute from
element["removeAttributes"].
Return modified.
Otherwise:
If configuration["removeAttributes"] contains attribute, then return false.
If configuration["elements"]
exists:
For each element in
configuration["elements"]:
If element["attributes"] with default « » contains attribute, then remove attribute from element["attributes"].
If element["removeAttributes"]
with default « » contains attribute, then remove attribute from element["removeAttributes"].
Append attribute to
configuration["removeAttributes"].
Return true.
To remove unsafe from a SanitizerConfig configuration:
Let result be false.
For each element in built-in safe
baseline configuration["removeElements"]:
If removing element from configuration is true, then set result to true.
For each attribute in built-in safe
baseline configuration["removeAttributes"]:
If removing attribute from configuration is true, then set result to true.
For each attribute that is an event handler content attribute:
If removing attribute from configuration is true, then set result to true.
If configuration["javascriptURLs"] is true:
Set result to true.
Set configuration["javascriptURLs"] to false.
Return result.
To compare sanitizer items itemA and itemB:
Let namespaceA be itemA["namespace"].
Let namespaceB be itemB["namespace"].
If namespaceA is null:
If namespaceB is not null, then return true.
Otherwise:
If namespaceB is null, then return false.
If namespaceA is code unit less than namespaceB, then return true.
If namespaceA is not namespaceB, then return false.
If itemA["name"] is
code unit less than itemB["name"], then return true.
Return false.
To canonicalize a SanitizerElementWithAttributes element:
Let result be the result of canonicalizing element.
If element is a dictionary:
If element["attributes"] exists, then set result["attributes"] to the
result of canonicalizing
element["attributes"].
If element["removeAttributes"]
exists, then set result["removeAttributes"]
to the result of canonicalizing
element["removeAttributes"].
If neither result["attributes"] nor
result["removeAttributes"]
exists, then set result["removeAttributes"]
to an empty list.
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.
Assert: config["elements"] exists
or config["removeElements"]
exists.
If config["elements"] exists and config["removeElements"] exists, then return false.
Assert: Either config["processingInstructions"] exists or config["removeProcessingInstructions"]
exists.
If config["processingInstructions"] exists and config["removeProcessingInstructions"]
exists, then return false.
Assert: Either config["attributes"] exists or config["removeAttributes"] exists.
If config["attributes"]
exists and config["removeAttributes"] exists, then return false.
Assert: All SanitizerElementNamespaceWithAttributes, SanitizerElementNamespace, SanitizerProcessingInstruction, and SanitizerAttributeNamespace items in config are canonical, meaning they have been run through canonicalizing, as appropriate.
If config["elements"]
has duplicates, then return false.
Otherwise:
If config["removeElements"] has duplicates, then return false.
If config["replaceWithChildrenElements"]
exists and has
duplicates, then return false.
If config["processingInstructions"] exists:
If config["processingInstructions"] has duplicates, then return false.
Otherwise:
If config["removeProcessingInstructions"]
has duplicates, then return false.
If config["attributes"] exists:
If config["attributes"]
has duplicates, then return false.
Otherwise:
If config["removeAttributes"] has duplicates, then return false.
If config["replaceWithChildrenElements"]
exists:
For each element of config["replaceWithChildrenElements"]:
If the built-in non-replaceable elements list contains element, then return false.
If the intersection of
config["elements"] and
config["replaceWithChildrenElements"]
is not empty, then return false.
Otherwise:
If the intersection of
config["removeElements"]
and config["replaceWithChildrenElements"]
is not empty, then return false.
If config["attributes"] exists:
Assert: config["dataAttributes"] exists.
For each element of
config["elements"]:
If element["attributes"] exists and element["attributes"] has duplicates, then return false.
If element["removeAttributes"]
exists and element["removeAttributes"]
has duplicates, then return false.
If the intersection of
config["attributes"] and
element["attributes"] with default « » is not empty, then return false.
If element["removeAttributes"]
with default « » is not a subset of config["attributes"], then return false.
If config["dataAttributes"] is true and
element["attributes"]
contains a custom data attribute, then return false.
If config["dataAttributes"] is true and
config["attributes"] contains a
custom data attribute, then return false.
Otherwise:
For each element of
config["elements"]:
If element["attributes"] exists and element["removeAttributes"]
exists, then return false.
If element["attributes"] exists and element["attributes"] has duplicates, then return false.
If element["removeAttributes"]
exists and element["removeAttributes"]
has duplicates, then return false.
If the intersection of
config["removeAttributes"] and
element["attributes"] with default « » is not empty, then return false.
If the intersection of
config["removeAttributes"] and
element["removeAttributes"]
with default « » is not empty, then return
false.
If config["dataAttributes"] exists, then return false.
Return true.
An element's sanitization category can be one of the following:
SanitizerConfig.setHTMLUnsafe() or parseHTMLUnsafe(), and removed by setHTML(), parseHTML(),
and 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:
processingInstructionsattributesdirlangtitlealignment-baselinebaseline-shiftclip-pathclip-rulecolorcolor-interpolationcursordirectiondisplaydisplaystyledominant-baselinefillfill-opacityfill-rulefont-familyfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-weightletter-spacingmarker-endmarker-midmarker-startmathbackgroundmathcolormathsizeopacitypaint-orderpointer-eventsscriptlevelshape-renderingstop-colorstop-opacitystrokestroke-dasharraystroke-dashoffsetstroke-linecapstroke-linejoinstroke-miterlimitstroke-opacitystroke-widthtext-anchortext-decorationtext-overflowtext-renderingtransformtransform-originunicode-bidivector-effectvisibilitywhite-spaceword-spacingwriting-modecommentsdataAttributesjavascriptURLselementsattributes 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):
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 | Element namespace | Attribute | Attribute namespace |
|---|---|---|---|
a
| SVG | href
| no namespace |
a
| SVG | href
| XLink |
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 | Element namespace | Attribute |
|---|---|---|
animate
| SVG | attributeName
|
animateTransform
| SVG | attributeName
|
set
| SVG | attributeName
|
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 | Element namespace |
|---|---|
html
| HTML |
svg
| SVG |
math
| MathML |
This section is non-normative.
The Sanitizer API is intended to prevent DOM-based cross-site scripting by traversing supplied
HTML content and removing elements and attributes according to a configuration. By design, the
setHTML() 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.
However, there are security issues that the Sanitizer API cannot prevent. The following sections describe them.
This section is non-normative.
The Sanitizer API operates solely in the DOM and adds a capability to traverse and filter an
existing DocumentFragment. The Sanitizer API does not address server-side reflected
or stored XSS.
This section is non-normative.
DOM clobbering describes an attack in which malicious HTML confuses an application by using
id or name attributes such that DOM
properties, such as the children property of an HTML
element, are shadowed by malicious content.
The Sanitizer API does not protect against DOM clobbering attacks by default, but can be
configured to remove id and name
attributes.
This section is non-normative.
Script gadgets are a technique in which an attacker uses existing application code from popular JavaScript libraries to cause their own code to execute. This is often done by injecting innocent-looking code or seemingly inert DOM nodes that are only parsed and interpreted by a framework which then performs the execution of JavaScript based on that input.
The Sanitizer API cannot prevent these attacks. Instead, it relies on authors to explicitly
allow unknown elements in general, and additionally to explicitly allow attributes, elements, and
markup commonly used for templating and framework-specific code, such as data-* and slot attributes and
elements like slot and template. These restrictions are not exhaustive
and authors are encouraged to examine their third party libraries for this behavior.
This section is non-normative.
Mutation XSS or mXSS describes an attack that exploits cases where the parsed DOM structure is not the same after serializing and parsing again, to bypass sanitization that happens before serialization. An example for carrying out such an attack is by relying on the change of parsing behavior for foreign content or mis-nested tags.
The Sanitizer API offers only functions that turn a string into a node tree. The context is supplied implicitly by all sanitizer functions: setHTML() uses the current element; Document.parseHTML() creates a new document. Therefore Sanitizer API is not directly affected by mutation XSS.
If a developer were to retrieve a sanitized node tree as a string, e.g. via innerHTML, and to then parse it again then mutation XSS can
occur. This practice is strongly discouraged. If processing or passing of HTML as a string is
necessary after all, then any string is to be considered untrusted and re-sanitized when inserted
into the DOM. In other words, a sanitized and then serialized HTML tree can no longer be
considered sanitized. A more complete treatment of mXSS can be found in [MXSS].