← Back to all snippets
JAVASCRIPT

Prevent XSS Attacks with JavaScript HTML Output Encoding

Safely display user-generated content in web applications by encoding HTML special characters in JavaScript to prevent XSS vulnerabilities.

/**
 * Encodes HTML special characters in a string to prevent XSS attacks.
 *
 * @param {string} str The string to encode.
 * @returns {string} The HTML-encoded string.
 */
function encodeHTML(str) {
    if (typeof str !== 'string') {
        return ''; // Or throw an error, depending on desired behavior
    }
    const div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}

// --- Example Usage ---
const userInput = "<script>alert('XSS Attack!');</script>";
const maliciousLink = '<a href="javascript:alert(\'Malicious Link!\')">Click Me</a>';
const userComment = "Hello <img src=x onerror=alert('Image XSS!')> World!";

// WITHOUT encoding (DANGEROUS!)
console.log("--- WITHOUT ENCODING (DANGEROUS) ---");
const containerDangerous = document.getElementById('output-dangerous');
if (containerDangerous) {
    containerDangerous.innerHTML = "User input: " + userInput + "<br>";
    containerDangerous.innerHTML += "Malicious link: " + maliciousLink + "<br>";
    containerDangerous.innerHTML += "User comment: " + userComment + "<br>";
} else {
    console.log("Output to DOM directly without encoding (simulated):");
    console.log("User input (raw): " + userInput);
    console.log("Malicious link (raw): " + maliciousLink);
    console.log("User comment (raw): " + userComment);
}


// WITH encoding (SECURE)
console.log("
--- WITH ENCODING (SECURE) ---");
const containerSecure = document.getElementById('output-secure');
if (containerSecure) {
    containerSecure.innerHTML = "Encoded user input: " + encodeHTML(userInput) + "<br>";
    containerSecure.innerHTML += "Encoded malicious link: " + encodeHTML(maliciousLink) + "<br>";
    containerSecure.innerHTML += "Encoded user comment: " + encodeHTML(userComment) + "<br>";
} else {
    console.log("Output to DOM using encoding (simulated):");
    console.log("Encoded user input: " + encodeHTML(userInput));
    console.log("Encoded malicious link: " + encodeHTML(maliciousLink));
    console.log("Encoded user comment: " + encodeHTML(userComment));
}


/*
// To run this in an HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XSS Prevention Example</title>
</head>
<body>
    <h1>XSS Prevention with JavaScript Encoding</h1>

    <h2>Output WITHOUT Encoding (DANGEROUS)</h2>
    <div id="output-dangerous" style="border: 1px solid red; padding: 10px;">
        <!-- Malicious content could execute here! -->
    </div>

    <h2>Output WITH Encoding (SECURE)</h2>
    <div id="output-secure" style="border: 1px solid green; padding: 10px;">
        <!-- Content displayed safely -->
    </div>

    <script>
        // Paste the JavaScript code here
        // ... (above encodeHTML function and examples)
    </script>
</body>
</html>
*/
How it works: Cross-Site Scripting (XSS) occurs when an attacker injects malicious client-side scripts into web pages viewed by other users. This JavaScript snippet provides a simple yet effective function, `encodeHTML`, to prevent XSS by safely displaying user-generated content. Instead of directly injecting user input into the DOM (e.g., using `innerHTML`), this function converts HTML special characters (`<`, `>`, `&`, `"`, `'`) into their corresponding HTML entities (`&lt;`, `&gt;`, `&amp;`, `&quot;`, `&#039;`). This ensures that the browser interprets the input as plain text rather than executable code, rendering it harmlessly. Always encode user-provided data before displaying it on your web pages.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs