JAVASCRIPT
Securely HTML Escaping User Input to Prevent XSS
Learn how to effectively HTML escape user-generated content before rendering it in the browser to protect your web application from Cross-Site Scripting (XSS) attacks.
function escapeHtml(str) {
if (typeof str !== 'string') {
return '';
}
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 sanitizedOutput = escapeHtml(userInput);
console.log(sanitizedOutput);
// Expected output: <script>alert('XSS Attack!');</script><b>Hello</b>
document.getElementById('user_display_area').innerHTML = sanitizedOutput;
// This will display the content safely, not execute the script.
How it works: This JavaScript function `escapeHtml` prevents XSS by converting special HTML characters (like `<`, `>`, `&`, `"`, `'`) into their corresponding HTML entities. It leverages the browser's DOM API by creating a temporary `div`, appending the raw text as a text node, and then retrieving its `innerHTML`. This method ensures that any malicious script tags in user input are rendered as text, not executed as code, making the output safe for display.