HTML Context Encoding
You'll learn how to safely insert untrusted data into HTML content by escaping special characters that could trigger XSS attacks.
When you insert user-provided data directly into HTML, special characters like <, >, &, ", and ' can break out of the intended context and execute malicious code. HTML context encoding transforms these dangerous characters into their harmless HTML entity equivalents.
Why This Matters
Imagine you're displaying a user's name on a page. If the name is Alice, everything works fine. But what if a malicious user enters <script>alert('XSS')</script> as their name? Without encoding, the browser interprets this as actual HTML and executes the script.
The Core Encoding Rules
When inserting untrusted data into HTML content (between tags like <div>user data here</div>), encode these characters:
<becomes<>becomes>&becomes&"becomes"'becomes'
Example
// DANGEROUS - No encoding
element.innerHTML = userInput; // ❌
// SAFE - With HTML context encoding
function encodeHTML(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
element.textContent = userInput; // ✅ Browser auto-encodes
// OR
element.innerHTML = encodeHTML(userInput); // ✅ Manual encoding
Context Matters
This encoding is specifically for HTML content contexts. Different contexts (attributes, JavaScript, CSS, URLs) require different encoding strategies—HTML entity encoding alone won't protect you everywhere.
Key Takeaway: Always HTML-encode untrusted data before inserting it into HTML content by converting special characters to HTML entities, preventing browsers from interpreting malicious markup as executable code.