Intermediate LevelHTML & Semantic Web
How do you sanitize untrusted raw user HTML against Cross-Site Scripting (XSS) attacks?
❓ Interview Prompt: Explain DOM-based XSS attacks, innerHTML dangers, and sanitizing HTML strings with DOMPurify.
Inserting unsanitized user HTML directly into the DOM via 'element.innerHTML' creates severe Cross-Site Scripting (XSS) vulnerabilities! Attackers can inject '<img src=x onerror="stealCookies()">' payloads.
Mitigation:
Sanitize raw user HTML strings using DOMPurify before inserting into the DOM tree!
Code Implementation Example
javascript
// Sanitize untrusted HTML payload using DOMPurify
const cleanHTML = DOMPurify.sanitize(untrustedUserString);
// Safe to insert sanitized HTML into DOM
document.getElementById('content').innerHTML = cleanHTML;💡Sanitizing raw user HTML strings with DOMPurify before DOM insertion.
🎯 Interview Key Takeaway
Never insert unsanitized user HTML via innerHTML. Use DOMPurify to strip XSS payloads safely.
#XSS#DOMPurify#Security#Sanitization#Intermediate
Back to all HTML & Semantic Web Questions→