javascript / intermediate
Snippet
Sanitizing Dynamic Rich Text Content to Prevent Cross-Site Scripting
Rendering raw user input using the v-html directive in Vue exposes applications to Cross-Site Scripting (XSS) attacks. By filtering HTML strings through DOMPurify inside a computed property, harmful script injections and malicious attributes are stripped while preserving safe formatting.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { ref, computed } from 'vue';import DOMPurify from 'dompurify';export function useSanitizedContent(rawHtmlInput) {const untrustedMarkup = ref(rawHtmlInput);const cleanHtml = computed(() => {return DOMPurify.sanitize(untrustedMarkup.value, {ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],ALLOWED_ATTR: ['href', 'target', 'rel']});});return { untrustedMarkup, cleanHtml };}
vue
Breakdown
1
const untrustedMarkup = ref(rawHtmlInput);
Initializes reactive state to hold the potentially hazardous user-supplied HTML string.
2
const cleanHtml = computed(() => {
Defines a computed property that automatically re-sanitizes content whenever the source markup changes.
3
return DOMPurify.sanitize(untrustedMarkup.value, {
Invokes the sanitization engine using an explicit allowlist configuration for elements and attributes.
4
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],
Restricts allowable HTML nodes to safe styling and anchor tags, neutralizing executable tags like script or iframe.