I was wondering if there is a programmatic way of sanitizing (user provided) URLs in AngularJs 1.5. I know there is $sanitize service, which is for sanitizing HTML but I can't find something that would work for URL.
Sample Good URL:
http://www.somedomain.com
Sample Dangerous URL:
javascript:document.write('Time for some fun');
There is undocumented $$sanitizeUri
service that does this. It's basically a function that adds unsafe
prefix to supplied URL . There's no need to use it for URLs are bound to href
like
<a href="{{url}}">
because this is already done by compiler ( $$sanitizeUri
is used there).
For malformed URLs in general it may be better to process them by hand and possibly add http://
if it doesn't contain acceptable (http/https) protocol.
I ended up performing the following regex test (inspired from $$sanitizeUri service ) on the URLs and then performing a special operation whenever the check failed.
function navigateToUrl(url) {
var safeWhiteListRegex = \^(https?|ftps?|file?):\/\/\gi;
if (!safeWhiteListRegex.test(url)) {
// url = ...;
} else {
$window.open(url, "_blank");
}
}
Along the way, one of my friends also discovered the @braintree/sanitize-url Node Module, which I also think is something people can use for situations like this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.