Lesson 3 of 9 · 24m
Parser Contexts and Dangerous Sinks
HTML text, attributes, URLs, script blocks, CSS, and event handlers each need different treatment — one sanitizer does not fit all.
The browser is not one parser. It is a pipeline of parsers and handoffs. Treating all output as "escaped" is how teams create bugs with a false sense of security: HTML-encoded content inside JavaScript can still execute, and a safe-looking attribute can become dangerous when the value is interpreted as a URL.
Context matrix
HTML text: <p>DATA</p>
Attribute: <input value="DATA">
URL attribute: <a href="DATA">
JS string: <script>const x = "DATA";</script>
CSS: <div style="color: DATA">
Markup sink: element.innerHTML = DATAEach row has a different attack surface. HTML text cares about tag formation. Attributes care about quote breakout and event handlers. URLs care about schemes such as javascript:. JavaScript strings care about quote termination, escapes, and </script>, which ends the script element even inside a string.
The dangerous sinks worth memorizing
el.innerHTML = value; // parses HTML
el.insertAdjacentHTML("beforeend", x); // parses HTML
document.write(value); // parses HTML during document load
eval(value); // executes JS
new Function(value)(); // executes JS
script.src = value; // loads executable URL
location.href = value; // javascript: in some legacy pathsFrameworks add their own versions: React dangerouslySetInnerHTML, Vue v-html, Angular [innerHTML] bypass patterns, lit-html unsafe directives. They are named dangerously for a reason.
Attribute context is subtler than people expect
<input value="{USER}">HTML encoding < and > is not enough if quotes are not encoded. x" autofocus onfocus="alert(1) breaks out cleanly. Unquoted attributes are worse because spaces, backticks in legacy browsers, and punctuation terminate the value.
URLs are not text
An attacker-controlled href does not need HTML metacharacters:
javascript:alert(document.domain)Allowlist URL schemes. Accept relative paths plus https: where appropriate; reject everything else. Decode before validation — %6aavascript: and HTML entity encodings are just obfuscation until the browser canonicalizes them.
Field notes
- Encoding must happen at the sink, once, with the right context encoder — not globally at input time.
- Never concatenate user input into JavaScript. Pass it as JSON into a data attribute or API response and read it as data.
innerTextandtextContentare safe assignment sinks;innerHTMLis markup compilation.- CSS is executable-adjacent: injection can alter layout, steal clicks, hide warnings, and sometimes exfiltrate attribute values.
Was this lesson helpful?