JAVASCRIPT

Sanitize User-Generated HTML Content with DOMPurify

Protect your web application from Cross-Site Scripting (XSS) by securely sanitizing untrusted HTML input using the robust DOMPurify library in JavaScript, ensuring safe content rendering.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOMPurify Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.min.js"></script>
</head>
<body>
    <h1>Sanitizing User HTML Input</h1>
    <textarea id="userInput" rows="10" cols="80">
<img src="x" onerror="alert('XSS Attack!');">
<a href="javascript:alert('Another XSS!');">Click Me</a>
<b>Safe bold text</b>
<style>body { background-color: red; }</style>
    </textarea>
    <button onclick="sanitizeAndDisplay()">Sanitize & Display</button>
    <h2>Cleaned Output:</h2>
    <div id="output"></div>

    <script>
        function sanitizeAndDisplay() {
            const userInput = document.getElementById('userInput').value;
            // DOMPurify.sanitize takes HTML string and returns a safe HTML string
            const cleanHTML = DOMPurify.sanitize(userInput, {
                USE_PROFILES: { html: true }, // Standard HTML cleaning profile
                FORBID_TAGS: ['style', 'script'], // Explicitly forbid certain tags if needed
                FORBID_ATTR: ['onerror', 'onclick'] // Explicitly forbid certain attributes
            });
            document.getElementById('output').innerHTML = cleanHTML;
            console.log('Original Input:
', userInput);
            console.log('Cleaned Output:
', cleanHTML);
        }
    </script>
</body>
</html>
How it works: This HTML/JavaScript snippet demonstrates how to securely sanitize user-generated HTML content using the `DOMPurify` library to prevent Cross-Site Scripting (XSS) attacks. User input, especially rich text, can contain malicious scripts or attributes. `DOMPurify.sanitize()` parses the input HTML and removes dangerous elements, attributes, and URLs based on a strict whitelist approach, ensuring that only safe HTML is rendered. The example shows how to configure `DOMPurify` with profiles and how to explicitly forbid certain tags or attributes, providing a robust defense against various XSS vectors when displaying untrusted content.

Need help integrating this into your project?

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

Hire DigitalCodeLabs