javascript / expert
Snippet
Contextual HTML Sanitization and CSP Nonce Verification in React Components
This security-focused React component enforces strict defenses against Cross-Site Scripting (XSS). It parses untrusted HTML through `DOMParser` in an isolated document scope, strips malicious tags and event handler attributes, and gates rendering behind Content Security Policy (CSP) nonce verification.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { useMemo } from 'react';function sanitizeUntrustedHTML(rawHtml) {const parser = new DOMParser();const doc = parser.parseFromString(rawHtml, 'text/html');const scripts = doc.querySelectorAll('script, iframe, object, embed');scripts.forEach((node) => node.remove());const allElements = doc.body.querySelectorAll('*');allElements.forEach((el) => {Array.from(el.attributes).forEach((attr) => {if (attr.name.startsWith('on') || attr.value.trim().startsWith('javascript:')) {el.removeAttribute(attr.name);}});});return doc.body.innerHTML;}export function SecureSafeHTML({ untrustedContent, cspNonce }) {const cleanHTML = useMemo(() => {if (!cspNonce) return '';return sanitizeUntrustedHTML(untrustedContent);}, [untrustedContent, cspNonce]);return (<divdata-nonce={cspNonce}dangerouslySetInnerHTML={{ __html: cleanHTML }}/>);}
react
Breakdown
1
const parser = new DOMParser();
Instantiates a browser DOMParser to convert raw string inputs into safe document AST trees in memory.
2
const scripts = doc.querySelectorAll('script, iframe, object, embed');
Queries hazardous executable HTML elements for structural removal prior to injection.
3
if (attr.name.startsWith('on') || attr.value.trim().startsWith('javascript:'))
Detects inline script event handlers (e.g., onerror, onload) and pseudoprotocol URI payloads to scrub them.
4
dangerouslySetInnerHTML={{ __html: cleanHTML }}
Mounts purified and sanitized HTML strings strictly after parsing validation and CSP checks.