Search code examples
javascripturlhrefsrc

how to implement if in javascript?


The javascript below extracts www.google.com from http://mysite.com?url=www.google.com and writes it as an <a> href link

<script> 
var urll = (window.location.search.match(/[?&;]url=([^&;]+)/) || [])[1]; 
document.write('<a href="http://'+urll+'">url</a>'); 
</script>

The problem with it is that when it extracts the url the <a> href value it becomes http://mysite.com/www.google.com so the if should state if the original url http://mysite.com?url=www.google.com doesn't have http:// infront of ?url= then add it after the href value to form <a href="http://www.google.com">url</a>

In a comment for a previous question someone gave me this

if (link.substr(0, 7) !== 'http://') { link = 'http://' + link; }

but I really don't have a clue on how to implement it because I have never used an if in javascript.


Solution

  • Apart from anything else you're making yourself suspectible to XSS attacks:

    Assume for a moment that the url parameter (which an external site can easily spoof by providing a link to your site) contains the string "><b>BOLD!</b><div class=". Suddenly your page would display some bold text, even 'though you never used a <b> tag in your site. And that's the most harmless example possible, because the attacker can equally well introduce arbitrary JavaScript into your page (including JS that steals the users cookie!).

    Moral of the story: never blindly trust user input, and don't simply convert it to HTML.

    To avoid these kinds of attacks (SQL Injection is a very similar attack against server-side code that builds SQL statements) do these two things:

    1. validate the input to ensure that it's exactly what you expect and don't accept it if it doesn't. In your case that would mean that you'd want to make sure that the url parameter actually represents a valid URL.
    2. Use user data only in "safe" ways that don't introduce the possibility of "re-interpretation" of the input. In your case it means that you must not build your HTML using string concatenation like this. Intead use document.createElement() to create your a element, set its href attribute to the desired value (sanitized as stated above) and then add the newly created a element in your DOM at the appropriate position.