JAVASCRIPT
Prevent Cross-Site Scripting (XSS) with HTML Encoding in JavaScript
Learn to prevent XSS attacks by properly encoding user-generated content before rendering it in HTML, ensuring malicious scripts are not executed.
function escapeHtml(str) {
const div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
// Example usage:
const userInput = "<script>alert('XSS Attack!');</script><b>Hello</b>";
const safeOutput = escapeHtml(userInput);
document.getElementById('output-area').innerHTML = `Rendered safely: ${safeOutput}`;
// The browser will display: Rendered safely: <script>alert('XSS Attack!');</script><b>Hello</b>
// Not as executable HTML
How it works: This snippet demonstrates a fundamental method to prevent Cross-Site Scripting (XSS) attacks by HTML-encoding user-provided input. It creates a temporary DOM element, assigns the text content, and then retrieves its `innerHTML`. This process automatically escapes special HTML characters (like `<`, `>`, `&`, `"`, `'`) into their respective HTML entities, rendering them harmless when injected into the DOM. Always encode untrusted data before displaying it on a web page to neutralize potential script injections.