Is it necessary to "escape" character "<" and ">" for javascript string?

Posted by Morgan Cheng on Stack Overflow See other posts from Stack Overflow or by Morgan Cheng
Published on 2009-04-23T01:27:41Z Indexed on 2010/03/30 21:53 UTC
Read the original article Hit count: 332

Filed under:
|
|
|

Sometimes, server side will generate strings to be embedded in inline JavaScript code. For example, if "UserName" should be generated by ASP.NET. Then it looks like.

<script>
   var username = "<%UserName%>";
</script>

This is not safe, because a user can have his/her name to be

</script><script>alert('bug')</script></script>

It is XSS vulnerability.

So, basically, the code should be:

<script>
   var username = "<% JavascriptEncode(UserName)%>";
</script>

What JavascriptEncode does is to add charater "\" before "/" and "'" and """. So, the output html is like. var username = "<\/script>alert(\'bug\')<\/script><\/script>";

Browser will not interpret "<\/script>" as end of script block. So, XSS in avoided.

However, there are still "<" and ">" there. It is suggested to escape these two characters as well. First of all, I don't believe it is a good idea to change "<" to "&lt;" and ">" to "&gt;" here. And, I'm not sure changing "<" to "\<" and ">" to "\>" is recognizable to all browsers. It seems it is not necessary to do further encoding for "<" and ">".

Is there any suggestion on this?

Thanks.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about encode