JAVASCRIPT
Prevent DOM-based XSS with `textContent` and Trusted Sanitization in JavaScript
Protect your web application from DOM-based Cross-Site Scripting (XSS) by prioritizing `textContent` over `innerHTML` and using trusted libraries for HTML sanitization.
// Scenario 1: Displaying plain text securely
const userInputText = "<script>alert('XSS via text!')</script>Dangerous text.";
const safeTextDiv = document.getElementById('safeTextDiv');
// CORRECT: Use textContent for plain text to prevent script execution
safeTextDiv.textContent = userInputText;
// INCORRECT: Avoid innerHTML for plain text, as it parses HTML/scripts
// safeTextDiv.innerHTML = userInputText;
// Scenario 2: Displaying trusted, sanitized HTML
// For cases where you MUST render HTML, use a trusted sanitization library.
// Example using DOMPurify (install via npm i dompurify or include via CDN)
// Assuming DOMPurify is loaded in the browser environment.
// import DOMPurify from 'dompurify'; // If using modules
const userSuppliedHTML = "<img src='x' onerror='alert(\"XSS via HTML!")'><b>User content</b>";
const unsafeHTMLDiv = document.getElementById('unsafeHTMLDiv');
// CORRECT: Sanitize user-provided HTML before injecting it
const cleanHTML = DOMPurify.sanitize(userSuppliedHTML);
unsafeHTMLDiv.innerHTML = cleanHTML;
// Note: DOMPurify needs to be loaded in the browser context.
// For Node.js, you'd use jsdom with DOMPurify.
// HTML structure for demonstration (would be in your .html file)
/*
<div id="safeTextDiv"></div>
<div id="unsafeHTMLDiv"></div>
*/
How it works: This JavaScript snippet illustrates crucial client-side practices to prevent DOM-based Cross-Site Scripting (XSS) attacks. For displaying plain text, it's vital to use `element.textContent` instead of `element.innerHTML`, as `textContent` automatically escapes HTML entities, preventing any embedded scripts from executing. When user-provided content *must* be rendered as HTML, a trusted sanitization library like DOMPurify is indispensable. DOMPurify meticulously cleans the HTML, removing malicious scripts and attributes while preserving legitimate markup, ensuring only safe HTML is injected into the DOM.