Comments, rich-text editors, emails and CMS fields all hand you HTML written by someone else, and showing it with innerHTML runs whatever it contains: <img src=x onerror=…>, a javascript: link, a <script>. A sanitizer turns untrusted HTML into HTML that is safe to insert, by keeping only what you explicitly allow. This is a security problem: a sanitizer that is right for ninety-nine inputs and wrong for one is a vulnerability.
functionsanitizeHtml(html, allowed) // returns a string of HTML
html: untrusted HTML (a fragment).
allowed: an object from lower-case tag name to the attribute names that tag may keep, for example { p: [], a: ["href", "title"], img: ["src", "alt"] }.
Parse the input into an inert tree (nothing runs or loads while you work), clean the tree, and return its HTML. Empty input gives "". Text is escaped in the output.
An element whose tag is an own key of allowed stays, with only the attributes its list names.
An element that is not allowed is unwrapped: it is removed and its (cleaned) children take its place.
These elements are removed with everything inside, even when allowed names them: script, style, template, iframe, frame, frameset, object, embed, noscript, noembed, noframes, xmp, plaintext, svg, math, base, link, meta.
Attributes whose name starts with on and the srcset attribute are always removed, even when listed.
URL attributes (href, src, cite, action, formaction, poster, background) are kept only if the URL is relative or uses http:, https: or mailto:, judged the way the browser reads it (case, spaces, tabs, newlines and character references cannot hide a javascript:). A kept URL keeps its original value.
Comments are removed.
Upper-case tags and attributes work, quotes in attribute values stay inside their attribute, and malformed or nested tricks (a broken <scr<script>ipt>, an unclosed tag, the noscript and mglyph mutations) leave nothing unsafe.
Cleaning the output again gives the same output.
The output inserted into a live page runs nothing. The allowlist object is not changed.