javascript / intermediate
Snippet
Preventing javascript: URI Injection in Dynamic React Anchor Hrefs
Passing unsanitized user strings into the `href` attribute of an `<a>` tag can allow cross-site scripting if the URL begins with `javascript:`. Parsing the input with the standard `URL` constructor verifies that the protocol matches safe schemes (`http:`, `https:`, `mailto:`) before binding it to JSX attributes.
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
function sanitizeExternalUrl(rawUrl) {try {const parsed = new URL(rawUrl, window.location.origin);const allowedProtocols = ['http:', 'https:', 'mailto:'];if (!allowedProtocols.includes(parsed.protocol)) {return '#';}return parsed.href;} catch {return '#';}}function SafeExternalLink({ userProvidedUrl, linkText }) {const safeHref = sanitizeExternalUrl(userProvidedUrl);const isSafe = safeHref !== '#';return (<ahref={safeHref}rel={isSafe ? 'noopener noreferrer' : undefined}target={isSafe ? '_blank' : undefined}>{linkText}</a>);}
react
Breakdown
1
const parsed = new URL(rawUrl, window.location.origin);
Parses the target string into a structured URL object against a base origin to check its components.
2
if (!allowedProtocols.includes(parsed.protocol)) {
Restricts navigation schemes exclusively to verified web and email transport protocols.
3
rel={isSafe ? 'noopener noreferrer' : undefined}
Attaches reverse-tabnabbing security attributes only when a valid external target URL exists.