JAVASCRIPT
Sanitize User-Generated HTML with DOMPurify for XSS Prevention
Protect your web application from Cross-Site Scripting (XSS) attacks by robustly sanitizing user-generated HTML content using the DOMPurify library.
// In a browser environment, DOMPurify would typically be loaded via a script tag or module bundler.
// Example: <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.min.js"></script>
// Or if using Node.js for server-side sanitization:
// const DOMPurify = require('dompurify')(require('jsdom').JSDOM);
// Assume DOMPurify is available in the scope
if (typeof DOMPurify === 'undefined') {
console.error("DOMPurify is not loaded. Please include it in your project.");
// Fallback or exit strategy if DOMPurify is critical
// For demonstration, we'll proceed with a mock object if it's not present.
var DOMPurify = { sanitize: (input) => `[DOMPurify MOCK] ${input.replace(/<script.*?>.*?<\/script>/gis, '')}` };
}
const userCommentInput = `
<p>This is a <b>safe</b> comment.</p>
<script>alert('XSS Attack!');<\/script>
<img src="x" onerror="alert('Another XSS!');">
<a href="javascript:alert('Even more XSS');">Click me</a>
<iframe src="malicious-site.com"></iframe>
<style>body { background-image: url('javascript:alert(1)'); }<\/style>
`;
// 1. Basic sanitization: Removes malicious elements and attributes
const cleanComment = DOMPurify.sanitize(userCommentInput);
console.log("--- Original Input ---");
console.log(userCommentInput);
console.log("
--- Sanitized Output (Default) ---");
console.log(cleanComment);
// Expected output for cleanComment will be something like:
// <p>This is a <b>safe</b> comment.</p>
// <img src="x">
// <a>Click me</a>
// <style>body { background-image: url(''); }<\/style>
const anotherInput = `
<p>Allowed attributes: <a href="https://example.com" target="_blank" rel="noopener noreferrer">Link</a></p>
<div id="malicious_id" onmouseover="alert('ID XSS');">Hover over me</div>
`;
// 2. Advanced sanitization with configuration options
// Allowing specific elements/attributes or disallowing others
const customConfigClean = DOMPurify.sanitize(anotherInput, {
USE_PROFILES: { html: true }, // Use a profile (e.g., HTML)
FORBID_ATTR: ['id', 'style'], // Forbid specific attributes globally
ALLOW_DATA_ATTR: false, // Disallow data-* attributes
ADD_TAGS: ['my-custom-tag'], // Allow a custom HTML tag
RETURN_DOM_FRAGMENT: false, // Return a string instead of a DocumentFragment
});
console.log("
--- Sanitized Output (Custom Config) ---");
console.log(customConfigClean);
// Expected:
// <p>Allowed attributes: <a href="https://example.com" target="_blank" rel="noopener noreferrer">Link</a></p>
// <div>Hover over me</div> (id and onmouseover removed)
// Example of displaying sanitized content
document.getElementById('output-div-safe').innerHTML = cleanComment;
document.getElementById('output-div-custom').innerHTML = customConfigClean;
How it works: This JavaScript snippet demonstrates how to use the DOMPurify library to sanitize user-generated HTML content, a critical step in preventing Cross-Site Scripting (XSS) attacks. When users submit rich text or HTML, malicious scripts or attributes can be embedded. DOMPurify intelligently cleans the HTML by removing unsafe elements, attributes, and URLs while preserving legitimate content. The snippet shows both basic sanitization and advanced configuration options, allowing developers to fine-tune what HTML is permitted, ensuring only safe content is rendered or stored.