DOM-Based XSS and Output Contexts
In a single-page application the server often sends a fixed bundle of JavaScript and some JSON, and the page builds itself in the browser. XSS then moves into that JavaScript: a value from the URL fragment, a postMessage, localStorage or an API response is written into the page through a property that parses HTML or a URL that can hold javascript:. The server may never see the payload at all (a fragment after # is not even sent), so server-side encoding and WAFs can't help. This is DOM-based XSS. JavaScript DOM Sinks introduced sources, sinks and innerHTML versus textContent; this lesson goes through the other contexts where the same value is dangerous in different ways, because the right fix depends on where the value lands.
Definitions
- Source: attacker-influenced data in the browser:
location.hash,location.search,document.referrer,window.name,postMessagedata,localStorage, API responses with user content. - Sink: an API that interprets its input: HTML sinks (
innerHTML,outerHTML,insertAdjacentHTML,document.write, jQuery.html()and$(html)), script sinks (eval,Function, stringsetTimeout), URL sinks (a.href,iframe.src,location = …,window.open) that acceptjavascript:URLs, and framework escape hatches (dangerouslySetInnerHTML,v-html,[innerHTML],bypassSecurityTrustHtml). - Contexts and their safe handling:
| Context | Example | Dangerous input | Safe handling |
|---|---|---|---|
| HTML text | el.innerHTML = 'Hi ' + v |
<img src=x onerror=…> |
textContent, or HTML-encode |
| HTML attribute | `<input value="${v}">` |
"><img src=x onerror=…> |
setAttribute('value', v) / el.value = v; attribute-encode including quotes |
| URL attribute | a.href = v |
javascript:…, data:text/html,… |
parse with new URL(), allow http:/https: (and mailto:) only |
| JavaScript code | `<script>var q = "${v}"</script>` |
";…;// or </script><script>… |
don't build code; pass data via JSON in a data- attribute or <script type="application/json"> |
| CSS | el.style = 'color:' + v |
red; background:url(…) |
allow-list values, style.setProperty |
Three contexts, one frame
The frame below writes the same kind of untrusted value into an attribute and a link, once unsafely and once safely. The values stand in for location.hash and a profile's "website" field; the payloads only write a line in the frame's own log.
<!doctype html>
<style>body{font:14px system-ui;margin:8px} .row{border:1px solid #999;padding:6px;margin:6px 0} pre{background:#8881;padding:6px}</style>
<div class="row" id="attr-unsafe"></div>
<div class="row" id="attr-safe"></div>
<div class="row"><a id="link-unsafe">unsafe website link</a> | <a id="link-safe">safe website link</a></div>
<pre id="log"></pre>
<script>
const log = (s) => { document.getElementById('log').textContent += s + '\n'; };
window.log = log;
// 1. Attribute context: a search box pre-filled from the URL fragment.
const fromHash = '"><img src=x onerror="log(\'attribute breakout ran\')">';
document.getElementById('attr-unsafe').innerHTML = `unsafe: <input value="${fromHash}">`;
const input = document.createElement('input');
input.value = fromHash; // property, not markup
document.getElementById('attr-safe').append('safe: ', input);
// 2. URL context: a "website" field from a user profile.
const website = 'javascript:log("javascript: URL ran")';
document.getElementById('link-unsafe').href = website;
function safeUrl(v) {
try {
const u = new URL(v, 'https://shop.lab.test/');
return ['http:', 'https:'].includes(u.protocol) ? u.href : 'about:blank';
} catch { return 'about:blank'; }
}
document.getElementById('link-safe').href = safeUrl(website);
log('safe link points to: ' + document.getElementById('link-safe').getAttribute('href'));
log('unsafe link points to: ' + document.getElementById('link-unsafe').getAttribute('href'));
</script>The unsafe input was built as a string of HTML, so the quote in the value closed the value attribute and the rest became a new <img> element whose handler ran. The safe input received the same text through the .value property and shows it literally. The unsafe link now carries a javascript: URL: on an ordinary page, a click on it runs the code in the page's origin. (Inside this sandboxed frame, a click on it can at most touch the frame itself, which is why the sandbox is a safe place for payloads.) The safe link was parsed with the URL parser, failed the scheme allow-list and became about:blank. HTML-encoding would not have helped the link at all: javascript:log(…) contains nothing to encode. That is why "encode everything" is not a complete rule: the context decides.
A reusable URL check
The URL check is worth having as a tested function. It runs in Node here, and the same code works in the browser:
function safeUrl(value, base = 'https://shop.lab.test/') {
try {
const u = new URL(value, base);
return ['http:', 'https:', 'mailto:'].includes(u.protocol) ? u.href : null;
} catch {
return null;
}
}
const inputs = [
'https://blog.lab.test/post/1',
'/account/settings',
'javascript:probe(1)',
' JavaScript:probe(1)',
'java\tscript:probe(1)',
'data:text/html,<script>probe(1)</script>',
'mailto:help@lab.test',
'//evil.example/path',
];
for (const v of inputs) console.log(JSON.stringify(v).padEnd(46), '->', safeUrl(v));"https://blog.lab.test/post/1" -> https://blog.lab.test/post/1
"/account/settings" -> https://shop.lab.test/account/settings
"javascript:probe(1)" -> null
" JavaScript:probe(1)" -> null
"java\tscript:probe(1)" -> null
"data:text/html,<script>probe(1)</script>" -> null
"mailto:help@lab.test" -> mailto:help@lab.test
"//evil.example/path" -> https://evil.example/path
The URL parser removes leading spaces and tabs inside the scheme exactly as the browser does, so the obfuscated javascript: variants are caught; a regular expression like /^javascript:/ would miss them. Note the last line: a protocol-relative URL is allowed by the scheme rule but points to another host; if links must stay on your site, also compare u.origin (see open redirects).
How DOM XSS is detected
- Code review / grep: list every sink (
innerHTML,outerHTML,insertAdjacentHTML,document.write,.html(,eval(,new Function,setTimeout(",href =,src =,location =,dangerouslySetInnerHTML,v-html,bypassSecurityTrust) and trace each one back to its sources. ESLint plugins (no-unsanitized) and Semgrep's JavaScript rules do the first pass. - Dynamic testing: put a marker in every source (
#xss'"<b>m</b>,?q=,postMessagefrom the console,localStoragevalues) and watch the DOM in DevTools; DOM Invader in Burp's browser automates this. - Trusted Types in report-only mode (
Content-Security-Policy-Report-Only: require-trusted-types-for 'script') reports every string that reaches an HTML or script sink in production, which is the most complete inventory you can get (XSS defences). - CSP reports:
script-src-attrandscript-src-elemviolations name the page and often the sink.
How it is fixed
- Prefer text APIs:
textContent,.value,setAttributefor non-URL, non-event attributes,createElement+append. - Let the framework render (React, Vue and Angular encode by default); review every escape hatch.
- URLs: parse and allow-list schemes (and origins where needed).
- No code from strings: no
eval,Function, string timers; pass data to scripts as JSON, never as code. - When HTML is required: sanitise with DOMPurify, ideally through a Trusted Types policy.
Pitfalls
textContenton a<script>element is a script sink, not a safe one.- jQuery's
$(value)creates elements whenvaluelooks like HTML, so$(location.hash)was a classic DOM XSS. - Encoding for HTML and then using the value in a URL or JavaScript context: wrong encoding is no encoding.
Practice
1. el.innerHTML = `<a href="${url}">profile</a>`, where url is HTML-encoded. Name the remaining hole and the fix.
javascript: URLs need no characters that HTML encoding changes. Build the element with createElement('a'), set a.href = safeUrl(url) and a.textContent = 'profile'.
2. A page does setTimeout("render('" + location.hash.slice(1) + "')", 0). What kind of sink is it and what is the fix?
A string setTimeout is a script sink (like eval). Use a function: setTimeout(() => render(location.hash.slice(1)), 0), and make render write text, not HTML.
Test yourself
Why can't server-side encoding prevent XSS from location.hash?
- Hashes are encrypted
- The fragment is never sent to the server; the page's own JavaScript puts it into the DOM
- Servers can't encode
- Hashes are always safe
Which assignment is a URL sink that can run script?
- el.textContent = v
- a.href = v
- input.value = v
- el.className = v
In the demo, why did the safe input not run the payload?
- CSP
- The value was set through the .value property, never parsed as HTML
- The payload was shorter
- Inputs can't contain quotes
Why is /^javascript:/i a poor URL check?
- It is slow
- Browsers ignore leading spaces and embedded tabs in schemes, so variants slip through; parse with new URL() and allow-list
- It blocks https
- Regex can't use i