JAVASCRIPT
Sanitize User-Generated HTML to Prevent XSS with DOMPurify
Utilize DOMPurify, a robust XSS sanitizer, to clean untrusted HTML input from users, effectively preventing cross-site scripting vulnerabilities in web applications.
// In a browser environment, you would typically load DOMPurify via a CDN or npm bundle
// <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.3.6/purify.min.js"></script>
// Example usage for sanitizing user input
function sanitizeUserInput(input) {
if (typeof DOMPurify === 'undefined' || !DOMPurify) {
console.error('DOMPurify is not loaded. Please ensure it is included in your project.');
return input; // Fallback, but highly insecure without DOMPurify
}
// DOMPurify.sanitize takes HTML string and returns a safe HTML string
// You can customize options for allowing/disallowing specific tags, attributes, etc.
const cleanHtml = DOMPurify.sanitize(input, {
USE_PROFILES: {
html: true, // Allow standard HTML tags
svg: true, // Allow SVG tags
mathml: true // Allow MathML tags
},
// For stricter control, you can define allowed tags/attributes explicitly
// ALLOWED_TAGS: ['b', 'i', 'p', 'a', 'img', 'div'],
// ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'style']
});
return cleanHtml;
}
// --- Demonstration ---
const unsafeInput = '<img src="x" onerror="alert(\'XSS Attack!\')">Hello <script>alert(\'Malicious code!\')</script><b>World</b>';
const safeInput = sanitizeUserInput(unsafeInput);
console.log('Original (unsafe):', unsafeInput);
console.log('Sanitized (safe):', safeInput);
// Example for injecting into DOM (e.g., a div element)
// document.getElementById('output').innerHTML = safeInput;
// For a Node.js environment, DOMPurify works with JSDOM for server-side sanitization.
How it works: This snippet demonstrates how to sanitize user-generated HTML content using the DOMPurify library to prevent Cross-Site Scripting (XSS) attacks. DOMPurify intelligently parses and cleans HTML strings, removing potentially malicious scripts, event handlers, and other dangerous attributes while preserving legitimate HTML. By ensuring only safe HTML is rendered, you effectively close a major vector for XSS vulnerabilities, protecting both your users and your application's integrity. The example shows basic usage and mentions common configuration options.