Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
The sanitizeFor()
method of the Sanitizer
interface is used to parse and sanitize a string of HTML for insertion into the DOM at some later point.
The method accepts the tag name of the eventual destination HTML element as a parameter, and returns an HTML element object (of that type) that contains the sanitized subtree as its child. This context is needed because the result of parsing an HTML string depends on where it is used. For example, <td>
elements are valid nodes when inserted into a <table>
but will be skipped/ignored when parsed into a <div>
.
The subtree must be inserted into an element of the same type as the returned object (and the original element
parameter). If the caller extracts the sanitized subtree from the object, for example by using innerHTML
, it is their responsibility to ensure the correct context is used when it is inserted in the DOM.
The default Sanitizer()
configuration strips out XSS-relevant input by default, including <script>
tags, custom elements, and comments. The sanitizer configuration may be customized using Sanitizer()
constructor options.
Note: Use Element.setHTML()
instead of this method if the target element is available for immediate update.