Sanitizer API example

Sanitizer API example. setHTML() filters untrusted HTML in the browser so you do not assign a string to innerHTML.

The problem

A comment field that you paint with innerHTML. The string is not yours. A filter you wrote last year misses the next payload. The page is the origin.

The method

Element.setHTML() parses the string and drops XSS-unsafe nodes, even if a custom Sanitizer would allow them. setHTMLUnsafe() obeys the sanitizer as written. No sanitizer on the unsafe path is close to innerHTML.

What to do

  1. Run setHTML(). The stage is the filtered tree. The serial is what remains.
  2. Construct a Sanitizer that would allow the payload. Run setHTMLUnsafe() and compare.

Element.setHTML()

XSS-safe. Drops script, event handlers, and the rest of the unsafe set, even if the sanitizer lists them. Uses the default sanitizer if you have not constructed one. The drop-in for innerHTML.

target.setHTML(untrustedString)
target.setHTML(untrustedString, { sanitizer })

new Sanitizer()

An allow list that includes the payload. Next setHTML() still drops XSS-unsafe. setHTMLUnsafe() does not.

const sanitizer = new Sanitizer({
  elements: ["p", "span", "script"],
  attributes: ["onclick"],
})

get()

Returns the current SanitizerConfig. This lab counts the arrays.

sanitizer.get()

Element.setHTMLUnsafe()

Obeys the sanitizer. No sanitizer means keep what the context allows. A surviving onclick is live if you click it. The script tag is in the tree. It does not run.

target.setHTMLUnsafe(untrustedString)
target.setHTMLUnsafe(untrustedString, { sanitizer })

All Web API labs

  • Notifications API example
  • EyeDropper API example
  • Translator API example