admin管理员组文章数量:1278988
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.
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.
Share Improve this question edited Jun 24, 2010 at 9:45 user373186 asked Jun 24, 2010 at 9:18 user373186user373186 695 bronze badges8 Answers
Reset to default 7If 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/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./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 plete 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();
}
本文标签:
版权声明:本文标题:c# - How can I make sure a string is clean for insertion into javascript Alert('error message') - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741242516a2364254.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论