Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make sure a string is clean for insertion into javascript Alert('error message')

I am trying to display an error to the user of a web page using a javascript alert popup, I currently have the following code to clean the error string:

errorMessage.Replace("'", "\'")

But this is not sufficient as some illegal characters are not being removed, is there a static method somewhere in the framework that will format my string for clean insertion into html?

Update: my initial question was slightly ambiguous. the string needs to be valid as in alert('this is some 'illegal text' that will not popup'); I will try Server.HtmlEncode, hopefully it will do the trick.

like image 907
user373186 Avatar asked Jun 24 '10 09:06

user373186


3 Answers

If you have a look at the AntiXSS module in the Web Protection Library, you'll find that it has a JavaScriptEncode(string) method for just this sort of thing.

like image 191
PhilPursglove Avatar answered Nov 15 '22 00:11

PhilPursglove


There's a simple solution...use the DataContractJsonSerializer and "serialize" the string value. By serializing the string to JSON, you're by definition ensuring that it'll work nicely inside an alert statement.

like image 30
jvenema Avatar answered Nov 14 '22 23:11

jvenema


You want to avoid XSS vulnerabilities, which is good. The following cheat sheet should assist you (and also contains a reference to code for escaping the string):

http://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

like image 42
Lucero Avatar answered Nov 15 '22 00:11

Lucero