JAVASCRIPT
Sanitizing User-Generated HTML Content
Securely process user-generated HTML content in web applications using DOMPurify to prevent Cross-Site Scripting (XSS) vulnerabilities effectively.
// In a browser environment, DOMPurify would be loaded via script tag or npm import
// For Node.js, you'd typically run DOMPurify on the server after installation via npm install dompurify jsdom
// Example using DOMPurify (browser context):
// Assume DOMPurify is available globally or imported
const dirtyHTML = `<h1>Hello</h1><script>alert('XSS!');</script><p onclick="alert('Clickjacking!')">Click me</p><img src="x" onerror="alert('Image XSS!')">`;
const cleanHTML = DOMPurify.sanitize(dirtyHTML, {
USE_PROFILES: { html: true }, // or specify custom allowed tags/attributes
FORBID_ATTR: ['style', 'on*'], // Forbid inline styles and event handlers
});
console.log("Original (Dirty) HTML:
", dirtyHTML);
console.log("Cleaned HTML:
", cleanHTML);
// Example with specific options (e.g., allowing only certain tags):
const evenStricterClean = DOMPurify.sanitize(
`<p>Only paragraphs and bold text allowed <b>like this</b>, <span>not this</span>.</p><a href="javascript:alert('evil')">Click</a>`,
{
ALLOWED_TAGS: ['p', 'b'],
ALLOWED_ATTR: [], // no attributes allowed
}
);
console.log("Even Stricter Clean HTML:
", evenStricterClean);
How it works: This snippet demonstrates sanitizing user-generated HTML content using the DOMPurify library. Directly rendering user-provided HTML can lead to Cross-Site Scripting (XSS) attacks. DOMPurify removes malicious code (like script tags, event handlers, and dangerous attributes) while preserving benign HTML. This ensures that only safe and intended content is displayed, preventing attackers from injecting client-side scripts or manipulating the DOM through user input.