JAVASCRIPT

HTML Sanitization to Prevent XSS Attacks in JavaScript

Implement robust HTML sanitization with DOMPurify in JavaScript. Effectively prevent Cross-Site Scripting (XSS) attacks in user-generated content, ensuring the secure display of dynamic data.

// First, ensure DOMPurify is loaded in your project.
// Via CDN: <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.min.js"></script>
// Via npm: import DOMPurify from 'dompurify';

function sanitizeUserInput(inputString) {
  if (typeof DOMPurify === 'undefined') {
    console.error('DOMPurify is not loaded. Please include it in your project.');
    return inputString; // Fallback, but insecure
  }
  // Sanitize the HTML string
  const cleanHtml = DOMPurify.sanitize(inputString, {
    USE_PROFILES: { html: true }, // Ensure basic HTML is allowed if needed
    FORBID_TAGS: ['script'], // Explicitly forbid script tags
    FORBID_ATTR: ['onerror', 'onload', 'onmouseover'], // Forbid common event handlers
    // Add other configuration options as per your security policy
    // e.g., ALLOW_TAGS, ALLOW_ATTR, ADD_TAGS, ADD_ATTR, etc.
  });
  return cleanHtml;
}

// Example Usage:
const maliciousInput = '<img src="x" onerror="alert(\'XSS Attack!\')">Hello <script>alert("You are hacked!");</script> World!';
const benignInput = '<h1>Welcome!</h1><p>Here is some <b>safe</b> content.</p>';

const sanitizedMalicious = sanitizeUserInput(maliciousInput);
const sanitizedBenign = sanitizeUserInput(benignInput);

console.log('Original malicious:', maliciousInput);
console.log('Sanitized malicious:', sanitizedMalicious);
// document.getElementById('output').innerHTML = sanitizedMalicious; // Displaying sanitized content

console.log('Original benign:', benignInput);
console.log('Sanitized benign:', sanitizedBenign);
// document.getElementById('output2').innerHTML = sanitizedBenign; // Displaying sanitized content

// Example with potentially dangerous link:
const dangerousLink = '<a href="javascript:alert(1)">Click Me</a>';
console.log('Sanitized dangerous link:', sanitizeUserInput(dangerousLink));
How it works: Cross-Site Scripting (XSS) attacks occur when an attacker injects malicious client-side scripts into web pages viewed by other users. This JavaScript snippet demonstrates how to use the DOMPurify library to sanitize user-generated HTML content before rendering it on the page. DOMPurify meticulously parses and cleans HTML, preventing the execution of harmful scripts and ensuring that only safe, whitelisted HTML elements and attributes are displayed, thereby protecting your users from XSS.

Need help integrating this into your project?

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

Hire DigitalCodeLabs