DOM-based XSS

DOM-based Cross-Site Scripting (XSS) is a client-side vulnerability where the attack payload is executed as a result of modifying the DOM environment in the victim's browser. The malicious data never reaches the server—instead, the client-side JavaScript code processes untrusted input and dynamically updates the page in an unsafe way.

How It Works

The vulnerability exists entirely in client-side code. JavaScript reads data from an attacker-controllable source (like location.hash, location.search, or document.referrer) and passes it to a dangerous sink (like innerHTML, eval(), or document.write()).

Example

Vulnerable JavaScript code that reads from the URL hash:

// Vulnerable code
var name = location.hash.substring(1);
document.getElementById('welcome').innerHTML = 'Hello ' + name;

// Attacker's URL
https://example.com/page#<img src=x onerror=alert(1)>

Common Sources and Sinks

Sources (attacker-controlled):

  • location.hash, location.search, location.href
  • document.referrer, document.cookie
  • postMessage data, localStorage

Dangerous Sinks:

  • innerHTML, outerHTML, document.write()
  • eval(), setTimeout(), setInterval()
  • element.src, element.href

Prevention

  • Use textContent instead of innerHTML when possible
  • Sanitize user input before using in DOM operations
  • Avoid dangerous sinks like eval()
  • Use DOMPurify or similar libraries for HTML sanitization

See Also