javascript / expert
Snippet
XSS Mitigation in Custom Vue Directives via Element Sanitization
This expert snippet demonstrates how to write a security-focused custom Vue directive that intercepts raw HTML input before rendering. By parsing strings inside an isolated DOMParser instance and removing executable script tags or frame elements, it prevents cross-site scripting (XSS) attacks in dynamic template injection contexts.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { Directive } from 'vue';export const vSanitizeHtml: Directive<HTMLElement, string> = {mounted(el, binding) {try {const rawInput = binding.value;if (typeof rawInput !== 'string') {throw new TypeError('v-sanitize-html directive requires a string value.');}const parser = new DOMParser();const doc = parser.parseFromString(rawInput, 'text/html');const scripts = doc.querySelectorAll('script, iframe, object');scripts.forEach((node) => node.remove());el.innerHTML = doc.body.innerHTML;} catch (err) {console.error('Directives sanitization failure:', err);el.textContent = '';}}};
vue
Breakdown
1
export const vSanitizeHtml: Directive<HTMLElement, string> = {
Declares a typed custom directive object adhering to Vue directive lifecycle hooks.
2
mounted(el, binding) {
Executes logic when the bound element is inserted into the target DOM hierarchy.
3
if (typeof rawInput !== 'string') { throw new TypeError(...); }
Enforces strict runtime type validation on the passed directive binding argument.
4
const doc = parser.parseFromString(rawInput, 'text/html');
Parses raw string content into an isolated DOM Document subtree for safe inspection.
5
scripts.forEach((node) => node.remove());
Traverses and strips executable script and frame elements before injection to neutralize XSS vulnerabilities.
6
el.innerHTML = doc.body.innerHTML;
Assigns sanitized HTML string content securely to the host element.
7
el.textContent = '';
Falls back to safe empty state on unexpected runtime errors.