JavaScript DOM Sinks: innerHTML, textContent and eval
Cross-site scripting (XSS) is what happens when text from an attacker is treated by the browser as code. In modern single-page applications much of the XSS is DOM-based: the server never sees the payload, because JavaScript in the page takes a value from the URL, a message or an API response and writes it into the page with a property that parses HTML. Reviewing front-end code for XSS is therefore mostly a search for those properties, called sinks, and for where their input comes from, the sources. This lesson shows the difference between a dangerous sink and a safe one inside a sandboxed frame on this page, then the same idea for eval. Web vulnerabilities in full are the subject of Web Application Security; the on-ramp is the survey's XSS lesson.
Definitions
- Source: where attacker-controllable data enters the page:
location.search,location.hash,document.referrer,postMessagedata,localStorage, an API response containing user content. - HTML sinks: properties and functions that parse a string as HTML:
innerHTML,outerHTML,insertAdjacentHTML,document.write, jQuery's.html(),$(…)with markup, React'sdangerouslySetInnerHTML, Vue'sv-html. - Script sinks:
eval,new Function,setTimeout("string"),setInterval("string"),<script>.text, and URL sinks such asa.href = "javascript:…". - Safe sinks:
textContent,innerText,setAttributefor non-event, non-URL attributes,createElement+append. They treat the value as text. - Trusted Types: a browser feature (enabled by the CSP directive
require-trusted-types-for 'script') that makes HTML and script sinks reject plain strings, so every write must pass through a reviewed policy.
The sink decides
The frame below renders a "search results" heading from a query string, as many pages do. The first version uses innerHTML, the second textContent. The query is a classic test payload: an image whose onerror handler runs JavaScript. Here the handler only writes a line into the frame's own log, which proves code ran; a real attacker would read the page or send requests as the victim. Edit the query and run it again.
<!doctype html>
<style>body{font:14px system-ui;margin:8px} .box{border:1px solid #999;padding:6px;margin:6px 0} #log{color:#b00}</style>
<p>Query: <code id="q"></code></p>
<div class="box">innerHTML: <span id="unsafe"></span></div>
<div class="box">textContent: <span id="safe"></span></div>
<div class="box">built with createElement: <span id="built"></span></div>
<pre id="log"></pre>
<script>
// In a real page this would come from location.search: an attacker-controlled source.
const query = '<img src=x onerror="document.getElementById(\'log\').textContent += \'script ran via innerHTML\\n\'">shoes';
document.getElementById('q').textContent = query;
document.getElementById('unsafe').innerHTML = 'Results for ' + query; // HTML sink: parses the payload
document.getElementById('safe').textContent = 'Results for ' + query; // text sink: shows it literally
const b = document.createElement('b'); // structure from code, data as text
b.textContent = query;
document.getElementById('built').append('Results for ', b);
</script>The innerHTML box shows a broken image and the red line in the log: the browser parsed the string, created an <img> element and ran its onerror handler. The textContent box shows the payload as harmless text. The third box builds the markup from code and inserts the data as text, which is how to get formatting without parsing input.
eval and its safe replacements
eval turns a string into code. It appears in old code that "parses" JSON, in calculators, and in configuration loaders. The example runs in Node (and in your browser) and only reads a variable in its own scope.
const secretInScope = 'session-token-of-the-victim';
function parseConfigUnsafe(text) {
return eval('(' + text + ')'); // runs anything
}
function parseConfigSafe(text) {
return JSON.parse(text); // data only
}
const normal = '{"theme": "dark", "items": 20}';
const hostile = '{"theme": "dark", "items": (console.log("eval ran, can read: " + secretInScope), 20)}';
console.log(parseConfigUnsafe(normal));
console.log(parseConfigUnsafe(hostile));
console.log(parseConfigSafe(normal));
try {
parseConfigSafe(hostile);
} catch (e) {
console.log('JSON.parse rejected it:', e.name);
}
// Escaping for the rare case where you must build HTML from data
const escapeHtml = (s) => String(s).replace(/[&<>"']/g,
(c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
console.log(escapeHtml('<img src=x onerror="probe()">'));{ theme: 'dark', items: 20 }
eval ran, can read: session-token-of-the-victim
{ theme: 'dark', items: 20 }
{ theme: 'dark', items: 20 }
JSON.parse rejected it: SyntaxError
<img src=x onerror="probe()">
The hostile "configuration" is valid JavaScript, so eval runs the console.log inside it, with access to everything in scope. JSON.parse accepts only JSON, which has no function calls, and throws a SyntaxError.
How DOM XSS is detected
- Code search for the sinks listed above, then trace each one back to a source. Tools: Semgrep rules for DOM XSS, ESLint
no-eval,no-implied-evalandeslint-plugin-no-unsanitized, CodeQL'sjs/xss-through-dom. - Browser testing: put a unique marker such as
xss"'<b>probe</b>into every input, URL parameter and fragment, and look in the DOM (DevTools Elements) for where it appears as markup. Burp Suite's DOM Invader automates this in a lab (see Web Application Security). - CSP violation reports: a policy with
report-tosends a report whenever an inline handler or a blocked script tries to run, which in production often means an injection attempt.
How it is fixed
- Use text sinks (
textContent,createElement, framework bindings like{value}in React or{{ value }}in Vue, which escape by default). - When HTML from users is a feature (rich text, comments), sanitize it with a maintained library such as DOMPurify, with a strict allowlist of tags and attributes, right before the sink.
- Never
evaldata.JSON.parsefor JSON, a real parser for expressions, a lookup table instead ofwindow[name](). - Content Security Policy without
'unsafe-inline'and'unsafe-eval'stops inline handlers likeonerrorandevaleven when a bug slips through;require-trusted-types-for 'script'turns every remaining sink into a reviewed one. - Validate URLs before
href/src: allow onlyhttps:(and maybemailto:), sojavascript:URLs can't be injected.
Pitfalls
- Escaping for the wrong context. HTML escaping is not enough inside a
<script>block, an event handler attribute, a URL or CSS; each context has its own rules. Avoid putting data there at all. innerTextis safe to write but not to read for security decisions: it reflects rendering and CSS.- Sanitize-then-modify: changing sanitized HTML afterwards (string replace, concatenation) can re-introduce markup.
- Framework escape hatches (
dangerouslySetInnerHTML,v-html,bypassSecurityTrustHtmlin Angular) areinnerHTMLwith a longer name.
Practice
1. In the frame, change the query to <b>bold</b> shoes. What does each box show, and is that a vulnerability?
The innerHTML box shows bold in bold, the others show the tags as text. No script runs, but the attacker controls the page's markup: they can add fake login forms or links (HTML injection), and with the right element a script. It is the same bug.
2. Which of these are sinks: el.textContent = x, el.insertAdjacentHTML('beforeend', x), setTimeout(x, 100), a.href = x, el.setAttribute('title', x)?
insertAdjacentHTML (HTML sink), setTimeout with a string (script sink) and a.href (URL sink: javascript: URLs). textContent and a title attribute are safe.
3. A page uses location.hash.slice(1) as a section name and writes it with innerHTML. Why don't the server logs show the attack?
The fragment after # is never sent to the server. DOM XSS through location.hash is invisible server-side; only client-side review, testing and CSP reports reveal it.
Test yourself
Which property is a safe sink for untrusted text?
- innerHTML
- outerHTML
- textContent
- insertAdjacentHTML
Why did the image's onerror handler run in the innerHTML box?
- Images always run scripts
- innerHTML parsed the string as HTML, created the img element and fired its error handler
- textContent is unsafe
- The sandbox was off
What is the safe replacement for eval when loading a configuration in JSON?
- new Function
- JSON.parse
- setTimeout
- innerHTML
Which CSP feature makes HTML sinks reject plain strings?
- default-src 'self'
- require-trusted-types-for 'script'
- upgrade-insecure-requests
- frame-ancestors 'none'