JAVASCRIPT

Client-Side XSS Prevention by Sanitizing HTML with DOMPurify

Safely render user-generated HTML content on the client-side by sanitizing it against Cross-Site Scripting (XSS) attacks using the robust DOMPurify library.

<!-- Include DOMPurify from a CDN or install via npm -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.min.js"></script> -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XSS Sanitization Example</title>
</head>
<body>
    <h1>User Comment Section</h1>
    <div id="commentInput">
        <textarea id="userComment" rows="5" cols="50"></textarea><br>
        <button onclick="addComment()">Add Comment</button>
    </div>
    <hr>
    <h2>Comments:</h2>
    <div id="commentsDisplay"></div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.min.js"></script>
    <script>
        function addComment() {
            const commentInput = document.getElementById('userComment');
            const rawComment = commentInput.value;

            // Sanitize the user input using DOMPurify
            const cleanComment = DOMPurify.sanitize(rawComment, { USE_PROFILES: { html: true } });

            const commentsDisplay = document.getElementById('commentsDisplay');
            const newCommentDiv = document.createElement('div');
            
            // Use innerHTML only with sanitized content
            newCommentDiv.innerHTML = `<p><strong>User:</strong></p>${cleanComment}`;
            commentsDisplay.appendChild(newCommentDiv);

            commentInput.value = ''; // Clear the input
        }

        // Example of malicious input
        document.addEventListener('DOMContentLoaded', () => {
            const exampleMaliciousComment = `
                <img src="x" onerror="alert('XSS Attack!');">
                <p>Hello world!</p>
                <script>alert('Another XSS!');</script>
                <a href="javascript:alert('JS XSS!');">Click Me</a>
            `;
            document.getElementById('userComment').value = exampleMaliciousComment;
        });

    </script>
</body>
</html>
How it works: This client-side snippet demonstrates how to prevent Cross-Site Scripting (XSS) attacks when displaying user-generated content in a web browser. XSS occurs when an attacker injects malicious scripts into web pages viewed by other users. The solution leverages the `DOMPurify` library to sanitize raw HTML input. `DOMPurify.sanitize()` meticulously parses the input, removes any potentially harmful elements, attributes, or protocols (like `javascript:` URLs), and returns a safe HTML string. This clean HTML can then be safely inserted into the DOM using `innerHTML`, ensuring that only benign content is rendered and malicious scripts are neutralized.

Need help integrating this into your project?

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

Hire DigitalCodeLabs