javascript / beginner
Snippet
Validating External Link Protocols against Script Execution in Vue
Malicious URLs starting with pseudo-protocols like 'javascript:' can execute arbitrary scripts when bound directly to href attributes. Checking that user-supplied URLs start only with trusted protocols like 'http://' or 'https://' prevents Cross-Site Scripting (XSS) attacks in component templates.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { ref, computed } from 'vue';export default {setup() {const userUrl = ref('javascript:alert(1)');const safeUrl = computed(() => {const isHttp = userUrl.value.startsWith('http://');const isHttps = userUrl.value.startsWith('https://');return (isHttp || isHttps) ? userUrl.value : '#';});return { userUrl, safeUrl };}};
vue
Breakdown
1
const userUrl = ref('javascript:alert(1)');
Holds the raw, untrusted URL string input from user data.
2
const isHttp = userUrl.value.startsWith('http://');
Verifies whether the URL string begins with the unencrypted HTTP protocol prefix.
3
const isHttps = userUrl.value.startsWith('https://');
Verifies whether the URL string begins with the secure HTTPS protocol prefix.
4
return (isHttp || isHttps) ? userUrl.value : '#';
Returns the original URL if valid, or a safe fallback anchor '#' if an unauthorized protocol is detected.