JAVASCRIPT
How to Safely Encode HTML for Display to Prevent XSS
Learn to protect your web applications from Cross-Site Scripting (XSS) attacks by properly encoding user-generated content before rendering it in HTML.
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>";
const outputDiv = document.getElementById('outputDiv');
if (outputDiv) {
outputDiv.innerHTML = escapeHTML(userInput);
}
// The above will render the script tag as text, not execute it.
How it works: This snippet provides a JavaScript function, `escapeHTML`, which safely encodes potentially malicious user input by creating a temporary DOM element, appending the text as a text node, and then retrieving its `innerHTML`. This method effectively converts special HTML characters (like `<`, `>`, `&`, `"`, `'`) into their corresponding HTML entities, preventing them from being interpreted as executable code in the browser and mitigating Cross-Site Scripting (XSS) vulnerabilities. Always sanitize user input before displaying it.