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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With