/**
* Escapes HTML entities in a string to prevent XSS attacks.
* @param {string} str The string to escape.
* @returns {string} The escaped string.
*/
function escapeHtml(str) {
const div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
// CORRECT: Always escape user-generated content before rendering it to HTML
const userInput = "";
const safeOutput = escapeHtml(userInput);
document.getElementById('output').innerHTML = safeOutput;
// This will render: <script>alert('You are hacked!');</script>
// instead of executing the script.
// Example of insecure usage (DO NOT DO THIS!):
// document.getElementById('insecure-output').innerHTML = userInput;
// For frameworks, use their built-in escaping mechanisms (e.g., React's JSX, Vue's {{ }}).