0 day streak
javascript / intermediate
Snippet

Sanitizing Dynamic Hyperlinks Against Script Injection

Binding dynamic URLs directly to `href` attributes in templates can expose applications to Cross-Site Scripting (XSS) attacks via `javascript:` or `data:` schemes. By encapsulating URL parsing inside a reactive computed property, protocol validation is enforced before untrusted string inputs reach the DOM layer.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { computed } from 'vue';
export function useSafeLink(rawUrlRef) {
const allowedProtocols = new Set(['http:', 'https:', 'mailto:']);
const sanitizedUrl = computed(() => {
try {
const parsed = new URL(rawUrlRef.value, window.location.origin);
return allowedProtocols.has(parsed.protocol) ? parsed.href : '#';
} catch {
return '#';
}
});
return { sanitizedUrl };
}
vue
Breakdown
1
const allowedProtocols = new Set(['http:', 'https:', 'mailto:']);
Initializes a strict whitelist of safe URI schemes using an efficient Set lookup structure.
2
const parsed = new URL(rawUrlRef.value, window.location.origin);
Constructs a native URL object to parse absolute or relative path strings safely against the current origin.
3
return allowedProtocols.has(parsed.protocol) ? parsed.href : '#';
Validates the protocol scheme against the allowlist, falling back to a harmless anchor placeholder upon failure.