XSS via innerHTML and How to Prevent It
Understand cross-site scripting and safe alternatives to innerHTML.
The Core Vulnerability
Setting el.innerHTML = userInput parses the string as HTML. If userInput contains <script> tags or event-handler attributes (onclick, onerror), the browser interprets them — executing attacker-controlled code on the page.
Why It Is Common
Any code that interpolates user data into HTML — server templates, client-side rendering — risks XSS if the data is not escaped. Single-page apps that build innerHTML from API responses are especially exposed when those responses include user content.
All lessons in this course
- Content Security Policy meta http-equiv
- XSS via innerHTML and How to Prevent It
- iframe Sandboxing and Permissions Policy
- HTTPS and Subresource Integrity