如何确保字符串是否干净以插入javascript警报('错误消息')

时间:2021-07-25 20:05:38

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:

我试图使用javascript警告弹出窗口向网页用户显示错误,我目前有以下代码来清除错误字符串:

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?

但这还不够,因为一些非法字符没有被删除,框架中是否有一个静态方法将格式化我的字符串以便干净地插入到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.

更新:我最初的问题有点含糊不清。字符串需要在alert中有效('这是一些不会弹出的'非法文本');我将尝试Server.HtmlEncode,希望它能做到这一点。

8 个解决方案

#1


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.

如果你看一下Web Protection Library中的AntiXSS模块,你会发现它有一个JavaScriptEncode(string)方法。

#2


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.

有一个简单的解决方案......使用DataContractJsonSerializer并“序列化”字符串值。通过将字符串序列化为JSON,您可以根据定义确保它在alert语句中很好地工作。

#3


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):

你想避免XSS漏洞,这很好。以下备忘单应该可以帮助您(并且还包含对转义字符串的代码的引用):

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

#4


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.

要转义字符串以便干净地插入到html中,您可以使用HttpUtility.HtmlEncode方法。我不确定这会帮助你使用javascript。

http://msdn.microsoft.com/en-us/library/73z22y6h.aspx

#5


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

如果您使用的是ASP.NET 4,则可以使用新的<%:%>语法对生成的字符串进行HtmlEncode,并使用AntiXSS或您喜欢的任何其他库替换默认编码器。 Phil Haack在使用AntiXss作为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:

在以前的版本中,您可以使用其他人建议的内容,HtmlEncode或AntiXss,如下所示:

alert('<%= HttpUtility.HtmlEncode(this.ErrorMessage) %>');

or

alert('<%= AntiXss.HtmlEncode(this.ErrorMessage) %>');

#6


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.

Joe的回答最接近,但没有考虑\ r \ n换行。我找不到将c#newline翻译成javascript等效的方法。

public static string EscapeAlertMessage(string value)
{
  value = value.Replace("\\", "\\\\");
  value = value.Replace("'", "\\'");
  value = value.Replace("\"", "\\\"");
  value = value.Replace(Environment.NewLine, "--");

  return value;
}

#7


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:

HttpUtility.HtmlEncode不会对单引号(')进行编码,也不适合编码要用作警报消息的字符串。我个人这样做:

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:

如果您的邮件包含多行,则可以用“\ n”替换它们 - 例如如果这些行由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:

或者,如果您不知道分隔符是什么(\ r \ n,\ n或\ r \ n),您可以使用:

value = value.Replace("\r", "\\r");
value = value.Replace("\n", "\\n");

#8


0  

I use the following function in my projects. It escpaes all possible characters for Javascript:

我在我的项目中使用以下函数。它为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();
    }

#1


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.

如果你看一下Web Protection Library中的AntiXSS模块,你会发现它有一个JavaScriptEncode(string)方法。

#2


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.

有一个简单的解决方案......使用DataContractJsonSerializer并“序列化”字符串值。通过将字符串序列化为JSON,您可以根据定义确保它在alert语句中很好地工作。

#3


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):

你想避免XSS漏洞,这很好。以下备忘单应该可以帮助您(并且还包含对转义字符串的代码的引用):

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

#4


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.

要转义字符串以便干净地插入到html中,您可以使用HttpUtility.HtmlEncode方法。我不确定这会帮助你使用javascript。

http://msdn.microsoft.com/en-us/library/73z22y6h.aspx

#5


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

如果您使用的是ASP.NET 4,则可以使用新的<%:%>语法对生成的字符串进行HtmlEncode,并使用AntiXSS或您喜欢的任何其他库替换默认编码器。 Phil Haack在使用AntiXss作为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:

在以前的版本中,您可以使用其他人建议的内容,HtmlEncode或AntiXss,如下所示:

alert('<%= HttpUtility.HtmlEncode(this.ErrorMessage) %>');

or

alert('<%= AntiXss.HtmlEncode(this.ErrorMessage) %>');

#6


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.

Joe的回答最接近,但没有考虑\ r \ n换行。我找不到将c#newline翻译成javascript等效的方法。

public static string EscapeAlertMessage(string value)
{
  value = value.Replace("\\", "\\\\");
  value = value.Replace("'", "\\'");
  value = value.Replace("\"", "\\\"");
  value = value.Replace(Environment.NewLine, "--");

  return value;
}

#7


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:

HttpUtility.HtmlEncode不会对单引号(')进行编码,也不适合编码要用作警报消息的字符串。我个人这样做:

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:

如果您的邮件包含多行,则可以用“\ n”替换它们 - 例如如果这些行由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:

或者,如果您不知道分隔符是什么(\ r \ n,\ n或\ r \ n),您可以使用:

value = value.Replace("\r", "\\r");
value = value.Replace("\n", "\\n");

#8


0  

I use the following function in my projects. It escpaes all possible characters for Javascript:

我在我的项目中使用以下函数。它为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();
    }