What is cross-site scripting (XSS) and how do I prevent it with JavaScript?
Asked on Sep 06, 2024
Answer
Cross-site scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users. Preventing XSS involves sanitizing and validating user input to ensure no harmful scripts are executed.
// Function to escape potentially dangerous characters
function escapeHTML(input) {
const div = document.createElement('div');
div.appendChild(document.createTextNode(input));
return div.innerHTML;
}
// Example usage
const userInput = "<script>alert('XSS');</script>";
const safeInput = escapeHTML(userInput);
console.log(safeInput); // Outputs: <script>alert('XSS');</script>
Additional Comment:
✅ Answered with JavaScript best practices.- The "escapeHTML" function creates a temporary DOM element to safely encode HTML entities.
- This approach prevents scripts from being executed by converting them into harmless text.
- Always validate and sanitize user inputs on both client and server sides for robust security.
- Consider using libraries or frameworks that automatically handle XSS protection.
Recommended Links:
← Back to All Questions