JAVASCRIPT
Sanitizing User-Generated HTML Content Before Display in JavaScript
Safely display user-provided HTML content in your web application by sanitizing it to prevent Cross-Site Scripting (XSS) vulnerabilities using DOMPurify.
// Ensure you have DOMPurify loaded, e.g., via CDN or npm
// <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.min.js"></script>
function sanitizeHtmlForDisplay(dirtyHtml) {
if (typeof DOMPurify === 'undefined') {
console.error('DOMPurify is not loaded. Please include it.');
return '';
}
// Configure DOMPurify options as needed.
// For example, to allow only specific tags and attributes:
const cleanHtml = DOMPurify.sanitize(dirtyHtml, {
USE_PROFILES: { html: true }, // Use a built-in profile for HTML
FORBID_ATTR: ['style', 'on*'], // Forbid inline styles and event handlers
ALLOW_TAGS: ['b', 'i', 'a', 'p', 'br', 'strong', 'em', 'ul', 'ol', 'li', 'blockquote', 'code'], // Only allow these tags
// ADD_ATTR: ['target'] // Example: if you want to allow target attribute for 'a' tags
});
return cleanHtml;
}
// Example Usage:
const userInput = '<p>Hello, <b>world</b>!</p><img src="x" onerror="alert(\'XSS!\')"><a href="javascript:alert(\'bad\')">Click me</a>';
const cleanOutput = sanitizeHtmlForDisplay(userInput);
console.log('Original Input:', userInput);
console.log('Sanitized Output:', cleanOutput);
// To render to DOM:
// document.getElementById('output-div').innerHTML = cleanOutput;
// Another example with different content
const commentInput = 'This is a comment with some <em>emphasis</em> and a <script>alert("evil!");</script> tag.';
const cleanComment = sanitizeHtmlForDisplay(commentInput);
console.log('Original Comment:', commentInput);
console.log('Sanitized Comment:', cleanComment);
How it works: This JavaScript snippet shows how to sanitize user-generated HTML content before it's displayed on a webpage, a critical step to prevent Cross-Site Scripting (XSS) attacks. It uses the `DOMPurify` library (which must be loaded), a highly-regarded XSS sanitizer. The `sanitize` function removes malicious scripts, invalid HTML, and unwanted attributes (like `onerror` or `on*` event handlers) while preserving safe HTML. Customizable options allow specifying allowed tags, attributes, and more, ensuring only safe content is rendered to the DOM.