6

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.

8 Answers 8

7

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.

0
3

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.

1

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

0

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

1
  • I quote "that will format my string for clean insertion into html"
    – Hinek
    Jun 25, 2010 at 19:49
0

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) %>');
0

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;
}
3
  • JavaScript's newline is just '\n'
    – Ryan Kinal
    Jun 24, 2010 at 12:15
  • That would be Replace(Environment.NewLine, "\\n");
    – Joe
    Jun 24, 2010 at 12:26
  • 1
    A string could contain any type of line break (\n, \r or \r\n) ... shouldn't it be a regex that replaces \r andor \n against a single \\n ?
    – Hinek
    Jun 25, 2010 at 20:00
0

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");
2
  • This was fixed in ASP.NET 4.0. HtmlEncode now replaces ' with &#39; Jun 24, 2010 at 12:29
  • HtmlEncode encodes string for use in HTML. To use string in JavaScript string literal, you must encode it as JavaScript string literal, not HTML. Jun 24, 2010 at 13:58
0

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();
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.