0 day streak
javascript / beginner
Snippet

Preventing Script Injection in Dynamic Anchor Links

Binding user-controlled strings directly to href attributes can allow Cross-Site Scripting (XSS) via the 'javascript:' URI scheme. Validating the URL protocol inside a computed property ensures only safe http and https protocols are rendered to the DOM.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
import { ref, computed } from 'vue';
const userProvidedUrl = ref('javascript:alert("xss")');
const sanitizedUrl = computed(() => {
const target = userProvidedUrl.value.trim();
const isSafeProtocol = target.startsWith('http://') || target.startsWith('https://');
return isSafeProtocol ? target : '#';
});
vue
Breakdown
1
const userProvidedUrl = ref('javascript:alert("xss")');
Holds potentially dangerous, untrusted user input.
2
const isSafeProtocol = target.startsWith('http://') || target.startsWith('https://');
Verifies that the target link strictly uses allowed web protocols.
3
return isSafeProtocol ? target : '#';
Returns the safe URL or falls back to '#' to prevent malicious script execution.