JAVASCRIPT
Secure HTML Output: Escaping User Input for XSS Prevention
Learn to safely display user-generated content in JavaScript by escaping HTML entities, effectively preventing Cross-Site Scripting (XSS) vulnerabilities in your web applications.
function escapeHTML(str) {
const div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
// Example Usage:
const userInput = "<img src='x' onerror='alert(\"XSS Attack!\")'>";
const safeOutput = escapeHTML(userInput);
// Instead of directly setting innerHTML:
// document.getElementById('output').innerHTML = userInput; // DANGEROUS!
// Safely inject into the DOM:
document.getElementById('output').innerHTML = safeOutput;
console.log(safeOutput); // <img src='x' onerror='alert("XSS Attack!")'>
// You would typically have an element with id="output" in your HTML
// <div id="output"></div>
How it works: This JavaScript function `escapeHTML` prevents XSS by converting special HTML characters (like `<`, `>`, `&`, `"`, `'`) into their corresponding HTML entities. It achieves this by creating a temporary `div` element, appending the untrusted string as a text node, and then retrieving the `innerHTML`. This process automatically escapes the characters, making them safe to display in the browser without executing malicious scripts.