Element: setHTML() method

https://news.ycombinator.com/rss Hits: 20
Summary

setHTML(input) setHTML(input, options) The setHTML() method provides an XSS-safe method to parse and sanitize a string of HTML into a DocumentFragment, and then insert it into the DOM as a subtree of the element. setHTML() drops any elements in the HTML input string that are invalid in the context of the current element, such as a <col> element outside of a <table>. It then removes any HTML entities that aren't allowed by the sanitizer configuration, and further removes any XSS-unsafe elements or attributes — whether or not they are allowed by the sanitizer configuration. If no sanitizer configuration is specified in the options.sanitizer parameter, setHTML() is used with the default Sanitizer configuration. This configuration allows all elements and attributes that are considered XSS-safe, thereby disallowing entities that are considered unsafe. A custom sanitizer or sanitizer configuration can be specified to choose which elements, attributes, and comments are allowed or removed. Note that even if unsafe options are allowed by the sanitizer configuration, they will still be removed when using this method (which implicitly calls Sanitizer.removeUnsafe()). setHTML() should be used instead of Element.innerHTML for inserting untrusted strings of HTML into an element. It should also be used instead of Element.setHTMLUnsafe(), unless there is a specific need to allow unsafe elements and attributes. Note that since this method always sanitizes input strings of XSS-unsafe entities, it is not secured or validated using the Trusted Types API. This example shows some of the ways you can use setHTML() to sanitize and inject a string of HTML. // Define unsanitized string of HTML const unsanitizedString = "abc <script>alert(1)<" + "/script> def"; // Get the target Element with id "target" const target = document.getElementById("target"); // setHTML() with default sanitizer target.setHTML(unsanitizedString); // Define custom Sanitizer and use in setHTML() // This allows only ele...

First seen: 2025-10-22 21:27

Last seen: 2025-10-23 16:31