Course contentsShow
← Security
Lesson 673 of 3,05214. Web Security - XSS and Content InjectionFree lesson

DOM-Based XSS Prevention

Implement safe DOM manipulation practices, avoid dangerous sinks, and use textContent over innerHTML where possible.

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)
  • outerHTML
  • document.write()
  • eval()
  • setTimeout() / setInterval() with string arguments
  • element.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 to textContent)
  • setAttribute() for non-event attributes
  • createTextNode() 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.