Document: parseHTML() static method

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

Want more browser support for this feature? Tell us why.

The parseHTML() static method of the Document object is an XSS-safe method to parse and sanitize a string of HTML using the HTML Sanitizer API in order to create a new Document instance.

Syntax

js
Document.parseHTML(input)
Document.parseHTML(input, options)

Parameters

input

A string defining HTML to be sanitized and injected into the shadow root.

options Optional

An options object with the following optional parameters:

sanitizer

A Sanitizer or SanitizerConfig object which defines what elements of the input will be allowed or removed, or the string "default" for the default sanitizer configuration. The method will remove any XSS-unsafe elements and attributes, even if allowed by the sanitizer. If not specified, the default Sanitizer configuration is used.

Note that if you're using the same configuration multiple times, it's expected to be more efficient to use a Sanitizer and modify it when you need to.

Return value

A Document.

Exceptions

TypeError

This is thrown if options.sanitizer is passed a:

  • SanitizerConfig that isn't valid. For example, a configuration that includes both elements and removeElements configuration settings.
  • string that does not have the value "default".
  • value that is not a Sanitizer, SanitizerConfig, or string.

Description

The parseHTML() method parses and sanitizes a string of HTML using the HTML Sanitizer API in order to create a new Document instance that is XSS-safe.

The resulting Document will have a content type of "text/html", a character set of UTF-8, and a URL of "about:blank".

It implements the same sanitization logic as all the other XSS-safe HTML setters.

The input HTML may include declarative shadow roots. If the string of HTML defines more than one declarative shadow root in a particular shadow host then only the first ShadowRoot is created — subsequent declarations are parsed as <template> elements within that shadow root.

parseHTML() should be used instead of Document.parseHTMLUnsafe(), unless there is a specific need to allow unsafe elements and attributes.

Specifications

Specification
HTML
# dom-parsehtml

Browser compatibility

See also