JAVASCRIPT
Prevent XSS Attacks with DOMPurify for HTML Sanitization
Secure your web application against Cross-Site Scripting (XSS) by sanitizing user-generated HTML content using the robust DOMPurify library in JavaScript.
<!-- Include DOMPurify library from a CDN in your HTML -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.3.8/purify.min.js"></script> -->
<div id="output"></div>
<script>
const userInput = "<img src='x' onerror='alert(\'XSS Attack!\')'><p>Hello, <b>user</b>!</p>";
// --- BAD PRACTICE: Direct injection (Vulnerable to XSS) ---
// document.getElementById('output').innerHTML = userInput;
// console.log("Unsafe HTML output:", document.getElementById('output').innerHTML);
// --- GOOD PRACTICE: Sanitize with DOMPurify ---
const cleanHtml = DOMPurify.sanitize(userInput);
document.getElementById('output').innerHTML = cleanHtml;
console.log("Clean HTML output:", cleanHtml);
// Example with custom configuration (e.g., allowing specific tags)
const userInputWithScript = "<script>alert('Evil script!');</script><p>Some content.</p>";
const customCleanHtml = DOMPurify.sanitize(userInputWithScript, {
USE_PROFILES: { html: true }, // Explicitly allow HTML profile
FORBID_TAGS: ['script'] // This is default, but explicit example
});
console.log("Clean HTML with script forbidden:", customCleanHtml);
const allowedTagsExample = DOMPurify.sanitize("<a href='javascript:alert(1)'>Click Me</a><br>Allowed tag: <b>bold</b>", {
ALLOWED_TAGS: ['b', 'br'], // Only allow bold and break tags
FORBID_ATTR: ['href'] // Forbid href attribute as it can contain javascript:
});
console.log("Clean HTML with allowed tags and forbidden attrs:", allowedTagsExample);
</script>
How it works: This JavaScript snippet demonstrates how to prevent Cross-Site Scripting (XSS) attacks by sanitizing potentially malicious user input before rendering it on a webpage. It utilizes the DOMPurify library, a robust and highly recommended HTML sanitization tool, to strip out dangerous elements and attributes, ensuring that only safe and intended HTML content is displayed, thus protecting users from injected scripts.