Sanitize HTML by keeping only allowlisted tags and attributes
A support forum lets users write replies with a little formatting: bold text, lists, links. The HTML comes straight from the browser, so it can contain anything, including scripts and onclick handlers. Before a reply is stored, it goes through an allowlist sanitizer: only the tags and attributes you explicitly allow survive.
Implement sanitizeHtml(html, allowed?). It returns the sanitized HTML as a string.
sanitizeHtml(html, allowed?) // => string
allowed maps a lowercase tag name to the list of attribute names that tag may keep. When it is omitted, use this default:
{
p: [], br: [], b: [], strong: [], i: [], em: [], code: [], pre: [],
ul: [], ol: [], li: [], blockquote: [],
a: ['href', 'title'],
}
<div><b>Hi</b></div> becomes <b>Hi</b>.script, style, iframe, object, embed and template. This applies even if the allowlist lists them.on is removed, even if the allowlist lists it.href or src attribute is kept only if it is relative (it has no scheme) or its scheme is http:, https: or mailto:. To find the scheme, first remove all whitespace and control characters (code points 0–32 and 127) from the value, then match letters, digits, +, - or . before the first :, starting with a letter. Schemes are case-insensitive. Otherwise, remove the attribute.innerHTML of the parsed fragment). Text is escaped by the browser when you serialize it, so <script> in the input stays harmless text.Do not assign the input to the innerHTML of a normal element such as a div. Even a detached div starts loading <img src="x" onerror="..."> and runs the handler. Parse into a <template> element (its content is inert) or use DOMParser.
sanitizeHtml('<p onclick="steal()">Hi <b>there</b><script>alert(1)</script></p>');
// => '<p>Hi <b>there</b></p>'
sanitizeHtml('<div class="note"><span>Keep</span> me</div>');
// => 'Keep me'
sanitizeHtml('<a href=" JavaScript:alert(1)" title="Docs">docs</a>');
// => '<a title="Docs">docs</a>'
sanitizeHtml('<img src="cat.png" alt="Cat" onerror="x()">', { img: ['src', 'alt'] });
// => '<img src="cat.png" alt="Cat">'
Tests compare your output with the expected HTML after both are parsed and serialized by the browser, so attribute quoting does not matter. Attribute order and text must match.