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 开发者_如何学Goto 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
To escape a string for clean insertion into html you can use HttpUtility.HtmlEncode
method. I'm not sure it this helps you with the javascript.
http://msdn.microsoft.com/en-us/library/73z22y6h.aspx
If you are using ASP.NET 4 you can use the new <%: %> syntax to HtmlEncode the generated string AND replace the default encoder with AntiXSS, or any other library you may prefer. Phil Haack explains how to do this in Using AntiXss as the default encoder for ASP.NET
This way you can write an alert like this:
alert('<%: this.ErrorMessage %>');
In previous versions you can use what others have suggested, either HtmlEncode or AntiXss like this:
alert('<%= HttpUtility.HtmlEncode(this.ErrorMessage) %>');
or
alert('<%= AntiXss.HtmlEncode(this.ErrorMessage) %>');
Thanks for the help but none of the answers presented gave me the complete solution.
Joe's answer was closest but it did not account for \r\n newline. I could not find a way to translate c# newline into a javascript equivalient.
public static string EscapeAlertMessage(string value)
{
value = value.Replace("\\", "\\\\");
value = value.Replace("'", "\\'");
value = value.Replace("\"", "\\\"");
value = value.Replace(Environment.NewLine, "--");
return value;
}
HttpUtility.HtmlEncode
will not encode a single quote (') and is not suitable for encoding a string to be used as an alert message. Personally I do it like this:
public static string EscapeAlertMessage(string value)
{
value = value.Replace("\\", "\\\\");
value = value.Replace("'", "\\'");
value = value.Replace("\"", "\\\"");
return value;
}
If your message contains multiple lines, you can replace them by "\n" - e.g. if the lines are separated by Environment.NewLine:
value = value.Replace(Environment.NewLine, "\\n");
Or if you don't know what the separators are (\r\n, \n or \r only) you could use:
value = value.Replace("\r", "\\r");
value = value.Replace("\n", "\\n");
I use the following function in my projects. It escpaes all possible characters for Javascript:
/// <summary>
/// Encodes a string to be represented as a string literal. The format
/// is essentially a JSON string.
///
/// Example Output: Hello \"Rick\"!\r\nRock on
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string EncodeJsString(string s)
{
StringBuilder sb = new StringBuilder();
foreach (char c in s)
{
switch (c)
{
case '\"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
case '\'':
sb.Append("\\'");
break;
default:
int i = (int)c;
if (i < 32 || i > 127)
{
sb.AppendFormat("\\u{0:X04}", i);
}
else
{
sb.Append(c);
}
break;
}
}
return sb.ToString();
}
精彩评论