AngularJs How to sanitize URL in the controller?

2.9k views Asked by At

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');
2

There are 2 answers

0
Parth Shah On

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.

1
Estus Flask On

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.