Sanitizer() constructor creates a new
Sanitizer object, which can be used to sanitize untrusted strings of HTML, or untrusted
DocumentFragment objects, making them safe for insertion into a document's DOM.
Sanitizer() configuration causes sanitizer operations to strip out XSS-relevant input by default, including
<script> tags, custom elements, and comments.
config option can be used to customize the sanitizer behavior.
new Sanitizer() new Sanitizer(config)
A sanitizer configuration object with the following options (referred to as
SanitizerConfigin the specification):
Booleanvalue set to
false(default) to remove custom elements and their children. If set to
true, custom elements will be subject to built-in and custom configuration checks (and will be retained or dropped based on those checks).
Booleanvalue set to
false(default) to remove HTML comments. Set to
truein order to keep comments.
allowElements creates a sanitizer that will drop any elements that are not in
dropElements create a sanitizer that will allow all elements except those in these properties.
dropElements are processed before
If you specify both properties, the elements in
dropElements will be discarded first, followed by any elements not in
So while it is possible to specify both types of properties at the same time, the intent can always be more clearly captured using just one type.
The same applies to
The examples below show a sanitization operation using the
This method takes as inputs a string of HTML to sanitize and the context (tag) in which it is sanitized, and returns a sanitized node object for the specified tag.
To simplify the presentation the result that is shown is actually the innerHTML of the returned object.
This example shows the result of sanitizing a string with disallowed
script element using the default sanitizer (in a
const unsanitized = "abc <script>alert(1)<" + "/script> def"; const sanitized = new Sanitizer().sanitizeFor("div", unsanitized); // Result (innerHTML of 'sanitized'): script will be removed: "abc alert(1) def"
|HTML Sanitizer API |
BCD tables only load in the browser