JAVASCRIPT
Sanitize User Input to Prevent XSS with DOMPurify (Browser/Node.js)
Protect your web application from Cross-Site Scripting (XSS) attacks by robustly sanitizing untrusted HTML user input using the DOMPurify library before rendering it.
/**
* Install DOMPurify: npm install dompurify
* For browser usage, include the script: <script src="dompurify.min.js"></script>
*/
// For Node.js (requires a DOM implementation like JSDOM)
const createDOMPurify = require('dompurify');
const { JSDOM } = require('jsdom');
// In a browser environment, DOMPurify is usually globally available as `window.DOMPurify`
// For Node.js, we need to create an instance with a JSDOM window
const window = new JSDOM('').window;
const DOMPurify = createDOMPurify(window);
function sanitizeHtmlInput(rawHtml) {
// DOMPurify.sanitize removes dangerous elements and attributes
// and returns a clean, safe HTML string.
const cleanHtml = DOMPurify.sanitize(rawHtml, {
USE_PROFILES: {
html: true, // Default: allow most HTML
svg: false, // Disallow SVG for potentially malicious content
mathml: false // Disallow MathML
},
// You can also customize allowed tags, attributes, etc.
// ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a'],
// ALLOWED_ATTR: ['href', 'target']
});
return cleanHtml;
}
// --- Example Usage ---
const userInput1 = "<img src='x' onerror='alert(\"XSS Attack!\")'>";
const userInput2 = "<p>Hello, <b>world</b>!</p><script>alert('malicious');</script>";
const userInput3 = "<a href='javascript:alert(\"XSS\")'>Click Me</a>";
const userInput4 = "<div onmouseover='console.log(\"mouseover\")'>Hover over me</div>";
console.log("Original 1: ", userInput1);
console.log("Sanitized 1: ", sanitizeHtmlInput(userInput1));
console.log("
Original 2: ", userInput2);
console.log("Sanitized 2: ", sanitizeHtmlInput(userInput2));
console.log("
Original 3: ", userInput3);
console.log("Sanitized 3: ", sanitizeHtmlInput(userInput3));
console.log("
Original 4: ", userInput4);
console.log("Sanitized 4: ", sanitizeHtmlInput(userInput4));
How it works: This JavaScript snippet demonstrates how to prevent Cross-Site Scripting (XSS) attacks by sanitizing user-provided HTML content using the `DOMPurify` library. XSS occurs when an attacker injects malicious client-side scripts into web pages viewed by other users. `DOMPurify.sanitize()` parses the raw HTML, removes any potentially dangerous elements (like `script` tags) or attributes (like `onerror`, `onmouseover`, `href` with `javascript:` schemes), and returns a clean, safe HTML string that can be safely rendered on the page without executing malicious code. It's crucial to use such a library whenever displaying user-generated HTML content.