DOM-Based XSS Prevention
What you'll learn: You'll discover how to safely manipulate the DOM without introducing client-side XSS vulnerabilities through dangerous JavaScript operations.
Understanding DOM-Based XSS Risk
DOM-Based XSS happens entirely in the browser when JavaScript reads untrusted data (like location.hash or document.referrer) and writes it unsafely to the page. Unlike reflected or stored XSS, the malicious payload never touches the server—it's purely a client-side execution flaw.
Safe DOM Manipulation Practices
Avoid Dangerous Sinks
Think of "sinks" as destinations where data flows. Some sinks execute code automatically and are dangerous when fed untrusted input:
innerHTML(parses and executes HTML/scripts)outerHTMLdocument.write()eval()setTimeout()/setInterval()with string argumentselement.setAttribute('onclick', ...)
Use Safe Alternatives
Instead, prefer safe sinks that treat data as text, not code:
// DANGEROUS: innerHTML interprets HTML
element.innerHTML = userInput; // XSS if userInput contains <script>
// SAFE: textContent treats everything as plain text
element.textContent = userInput; // No HTML parsing, just displays text
Other safe approaches:
innerText(similar totextContent)setAttribute()for non-event attributescreateTextNode()for explicit text nodes
Validate and Sanitize Sources
When reading from user-controllable sources like location.search or window.name, always validate expected formats before using them. If you must insert HTML, use a trusted sanitization library (though this topic comes later in your learning path).
Key Takeaway: Prevent DOM-Based XSS by avoiding dangerous sinks like innerHTML and eval(), using textContent for displaying user-controlled data, and treating all client-side input sources as untrusted until validated.