JavaScript Interview Question #139

Why is innerHTML dangerous with untrusted input?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

innerHTML parses assigned text as HTML. If untrusted data reaches a dangerous HTML context, an attacker may be able to inject executable markup or otherwise manipulate the document.

Detailed Explanation

innerHTML parses assigned text as HTML. If untrusted data reaches a dangerous HTML context, an attacker may be able to inject executable markup or otherwise manipulate the document.

For plain text, use textContent. If an application genuinely needs to render user-controlled HTML, use a well-maintained sanitization approach designed for that purpose and still consider browser defenses such as Content Security Policy.

Code Example

const output = document.querySelector("#output");
const comment = getUserComment();

// Preferred when the content should be plain text:
output.textContent = comment;

// Do not do this with untrusted input:
// output.innerHTML = comment;