javascript / intermediate
Snippet
Validating Dynamic Anchor URLs to Prevent JavaScript Pseudo-Protocol Injection
Passing unsanitized dynamic user input directly into an `href` attribute allows attackers to inject `javascript:...` pseudo-protocols. Validating URLs with the native `URL` API ensures only safe protocols execute while `rel="noopener noreferrer"` guards against reverse tabnabbing.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import React from 'react';const ALLOWED_PROTOCOLS = ['https:', 'http:', 'mailto:'];export function SafeExternalLink({ href, children, ...rest }) {const isSafeProtocol = (targetUrl) => {try {const parsed = new URL(targetUrl, window.location.origin);return ALLOWED_PROTOCOLS.includes(parsed.protocol);}catch {return false;}};const safeHref = isSafeProtocol(href) ? href : '#';return (<ahref={safeHref}target="_blank"rel="noopener noreferrer"{...rest}>{children}</a>);}
react
Breakdown
1
const parsed = new URL(targetUrl, window.location.origin);
Parses the input string using the browser standard URL constructor to extract protocol components.
2
return ALLOWED_PROTOCOLS.includes(parsed.protocol);
Checks the parsed URL scheme against a strict allowlist to disallow unsafe schemes like javascript:.
3
rel="noopener noreferrer"
Prevents the target page from accessing window.opener and avoids sending referrer headers.