Created
June 28, 2021 17:59
-
-
Save josht-jpg/4c2d16f23480a10aad8489f29c12b0db to your computer and use it in GitHub Desktop.
Philippe De Ryck's adaptation of AngularJs's URL sanitizer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file|sms):|[^&:/?#]*(?:[/?#]|$))/gi; | |
/** A pattern that matches safe data URLs. It only matches image, video, and audio types. */ | |
const DATA_URL_PATTERN = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+\/]+=*$/i; | |
function _sanitizeUrl(url: string): string { | |
url = String(url); | |
if (url === "null" || url.length === 0 || url === "about:blank") return "about:blank"; | |
if (url.match(SAFE_URL_PATTERN) || url.match(DATA_URL_PATTERN)) return url; | |
return `unsafe:${url}`; | |
} | |
export function sanitizeUrl(url = "about:blank"): string { | |
return _sanitizeUrl(String(url).trim()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment