security security_error ai_generated true

XSS: Unsafe use of innerHTML with user-controlled data

ID: security/xss-innerhtml

Also available as: JSON · Markdown
90%Fix Rate
88%Confidence
3Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
any active

Root Cause

Setting innerHTML with user input enables Cross-Site Scripting attacks.

generic

Workarounds

  1. 95% success Use textContent/innerText instead of innerHTML
    element.textContent = userInput
  2. 90% success Use DOMPurify to sanitize HTML before insertion
    element.innerHTML = DOMPurify.sanitize(userInput)

Dead Ends

Common approaches that don't work:

  1. Sanitize with regex replace of script tags 85% fail

    XSS payloads use img onerror, svg onload, and many other vectors beyond script tags.

  2. Encode only < and > characters 80% fail

    Misses attribute-context XSS, javascript: URLs, and event handlers.