JAVASCRIPT
Sanitizing User Input for XSS Prevention (Client-side JavaScript with DOMPurify)
Effectively prevent Cross-Site Scripting (XSS) attacks by sanitizing user-generated HTML content on the client-side using the robust DOMPurify library in JavaScript.
import DOMPurify from 'dompurify'; // npm install dompurify
function sanitizeHtmlInput(rawHtml) {
// DOMPurify.sanitize() returns a clean HTML string.
// It removes potentially malicious content (scripts, event handlers, etc.).
const cleanHtml = DOMPurify.sanitize(rawHtml, {
USE_PROFILES: { html: true }, // Ensure basic HTML tags are allowed
FORBID_TAGS: ['style', 'script'], // Example: explicitly forbid certain tags
FORBID_ATTR: ['style', 'onerror', 'onload'], // Example: explicitly forbid attributes
});
return cleanHtml;
}
// Example Usage:
const maliciousInput = '<img src="x" onerror="alert(\'XSS Attack!\')">' +
'<a href="javascript:alert(\'Malicious Link!\')">Click Me</a>' +
'<p>Hello <script>alert(\'Another XSS!\')</script> World</p>'+
'<style>body{background-color:red;}</style>';
const safeInput = sanitizeHtmlInput(maliciousInput);
console.log('Original Input:', maliciousInput);
console.log('Sanitized Output:', safeInput);
// To display sanitized content in the DOM:
// const outputDiv = document.getElementById('output');
// if (outputDiv) {
// outputDiv.innerHTML = safeInput;
// }
// Another example with allowed tags
const richTextInput = '<h1>My Title</h1><p>Some <b>bold</b> text.</p><img src="safe.jpg">';
const safeRichText = sanitizeHtmlInput(richTextInput);
console.log('Sanitized Rich Text:', safeRichText);
How it works: This JavaScript snippet demonstrates client-side sanitization of user-generated HTML content using the 'DOMPurify' library. Cross-Site Scripting (XSS) attacks occur when malicious scripts are injected into web pages viewed by other users. DOMPurify robustly cleans HTML by removing dangerous tags, attributes, and scripts, ensuring that only safe content is rendered. While server-side sanitization is crucial, client-side sanitization adds an extra layer of defense, especially in Single Page Applications (SPAs) where content might be dynamically inserted into the DOM. Always remember that both client-side and server-side validation/sanitization are necessary.