You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
28 lines
614 B
28 lines
614 B
type SafeExternalHrefOptions = {
|
|
allowMailto?: boolean
|
|
}
|
|
|
|
export function safeExternalHref(raw: unknown, options: SafeExternalHrefOptions = {}): string | undefined {
|
|
if (typeof raw !== 'string') {
|
|
return undefined
|
|
}
|
|
const value = raw.trim()
|
|
if (!value) {
|
|
return undefined
|
|
}
|
|
|
|
try {
|
|
const url = new URL(value)
|
|
const protocol = url.protocol.toLowerCase()
|
|
if (protocol === 'http:' || protocol === 'https:') {
|
|
return url.href
|
|
}
|
|
if (options.allowMailto && protocol === 'mailto:') {
|
|
return url.href
|
|
}
|
|
return undefined
|
|
}
|
|
catch {
|
|
return undefined
|
|
}
|
|
}
|
|
|