Escaping special JavaScript characters from ASP.NET

I have C # code in my ASP.NET application:

string script = @"alert('Message head:\n\n" + CompoundErrStr + " message tail.');";
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Test", script, true);

CompoundErrStr is an error message generated by SQL Server (exception text is called from a stored procedure). If it contains table column names, they are enclosed in single quotes and JavaScript breaks at runtime because single quotes are considered string delimiters.

As a fix for single quotes, I changed my code to this:

CompoundErrStr = CompoundErrStr.Replace("'", @"\'");
string script = @"alert('Message head:\n\n" + CompoundErrStr + " message tail.');";
System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Test", script, true);

and now it works great.

However, are there any other special characters to avoid? Is there a .Net function that can be used for this purpose? Something similar to HttpServerUtility.HtmlEncode, but for JavaScript.

EDIT I am using .Net 3.5

+4
2

: ( ) HTML- (, HttpServerUtility.HtmlEncode()), HTML JavaScript . : "Check your Windows folder c:\windows" "Check your Windows folder c:'windows", . , HTML, \, " '. - .

? (\, " '), JavaScript, HTML, ( JS HTML-). : escape- JavaScript \ \uxxxx Unicode ( , \uxxxx, , HTML).

( ) :

string JavaScriptEscape(string text)
{
    return text
        .Replace("\\", @"\u005c")  // Because it JS string escape character
        .Replace("\"", @"\u0022")  // Because it may be string delimiter
        .Replace("'", @"\u0027")   // Because it may be string delimiter
        .Replace("&", @"\u0026")   // Because it may interfere with HTML parsing
        .Replace("<", @"\u003c")   // Because it may interfere with HTML parsing
        .Replace(">", @"\u003e");  // Because it may interfere with HTML parsing
}

, \ , escape-! (, , ). , , ). , # Unicode #, . HTML: <script> node DOM, , + "</s" + "cript>", .

. , , escape- (, \uxxxx \t), . .

, , , JavaScript :

alert("This is a multiline
comment");

.Replace("\n", "\\n").Replace("\r", "") JavaScriptEscape().


.NET 4 ( ), , HttpUtility.JavaScriptStringEncode( ).

: , Uri.EscapeDataString(), JavaScript decodeURIComponent(), , .


ASP.NET Core, System.Text.Encodings.Web.JavaScriptEncoder.

+6

.NET 3.5, 4.0+, HttpUtility.JavaScriptStringEncode("string")

bool , (true) (false) .

+5

Source: https://habr.com/ru/post/1568021/


All Articles