Dangerous innerHTML and DOM APIs
You'll learn why certain DOM APIs bypass browser protections and can reintroduce XSS vulnerabilities even when frameworks handle escaping automatically.
The Core Problem
Even though modern frameworks auto-escape variables (as you learned in "Framework Auto-Escaping"), some DOM APIs directly interpret strings as HTML or executable code. When you pass user input to these APIs, you're essentially handing an attacker a megaphone directly into your page's execution context.
The most dangerous culprits are:
innerHTML– Parses strings as HTML, executing embedded scripts in some contextsouterHTML– Replaces entire elements with parsed HTMLdocument.write()– Injects raw HTML into the document streaminsertAdjacentHTML()– Inserts HTML at specified positions
Why They're Dangerous
Think of these APIs as backdoors that skip the security guard. Your framework might sanitize data going through normal rendering, but when you write:
element.innerHTML = userComment; // DANGEROUS!
You're telling the browser: "Trust this string completely—parse it as HTML." If userComment contains <img src=x onerror=alert('XSS')>, that script executes.
The Safe Alternative
Use textContent or innerText for plain text, which treats everything as literal text, not markup:
element.textContent = userComment; // SAFE
For actual HTML needs, create elements programmatically using createElement() and appendChild(), or let your framework handle it.
Key Takeaway: Never pass untrusted user input to innerHTML, outerHTML, document.write(), or similar APIs—they bypass security mechanisms and create direct XSS vulnerabilities. Use textContent for text or framework-managed rendering for HTML.