JAVASCRIPT

Safely Sanitize User-Generated HTML to Prevent XSS Attacks with DOMPurify

Protect your web application from Cross-Site Scripting (XSS) by securely sanitizing user-provided HTML content on the client-side using the robust DOMPurify library.

// In a browser environment, you'd typically include DOMPurify via a script tag
// <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.min.js"></script>

// Or if using a module bundler like Webpack/Rollup (install via npm: npm install dompurify)
// import DOMPurify from 'dompurify';

// Simulate user input containing potentially malicious HTML
const userInput = `
  <h1>Welcome!</h1>
  <p>Here's some content from a user:</p>
  <img src="x" onerror="alert('XSS Attack!');" alt="malicious image">
  <a href="javascript:alert('Another XSS!');">Click Me</a>
  <p style="color: red;">This is some styled text.</p>
  <script>alert('Inline Script XSS!');</script>
  <div>Hello World!</div>
`;

console.log("Original User Input:
", userInput);

// Sanitize the user input using DOMPurify
// DOMPurify.sanitize takes a string and returns a purified string
const cleanHTML = DOMPurify.sanitize(userInput, {
  USE_PROFILES: { html: true }, // Ensure basic HTML parsing
  // Optional: customize allowed tags, attributes, etc.
  // ALLOWED_TAGS: ['p', 'h1', 'div'],
  // ALLOWED_ATTR: ['class', 'style'],
});

console.log("
Cleaned HTML Output:
", cleanHTML);

// To demonstrate, inject it into the DOM
// const outputDiv = document.createElement('div');
// outputDiv.innerHTML = cleanHTML;
// document.body.appendChild(outputDiv);

// Example of what would happen if not sanitized (DO NOT RUN IN PROD)
// const dangerousDiv = document.createElement('div');
// dangerousDiv.innerHTML = userInput;
// document.body.appendChild(dangerousDiv);
How it works: This JavaScript snippet demonstrates how to prevent Cross-Site Scripting (XSS) attacks by sanitizing user-generated HTML content using the `DOMPurify` library. `DOMPurify.sanitize()` removes any potentially malicious tags, attributes, and JavaScript from the input string, ensuring that only safe HTML is rendered. This is crucial when displaying user-contributed content to prevent attackers from injecting malicious scripts that could steal data or compromise user sessions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs