简体   繁体   中英

Javascript crashes on special characters from query string

To use this value in my TypeScript I am getting it from my query string like this:

var UserName = @Request.QueryString["UserName"];

But I get a Unexpeted Identifier error on it because if in DevTool if I go to where it breaks that query string has a value like this:

var UserName = ANT -- ANT 37690 / THIRD PARTY

So is there a way to do some kind of sanitation on it so it wouldn't crash? I guess there are illegal characters in that value for JS ?

The error has nothing to do with "special" characters, but with the fact that the right side of the assignment - unwrapped in quotes - contains what js engine views as unknown identifier[s].

One way to properly format data that becomes part of javascript code is to use JavaScriptSerializer class from System.Web.Script.Serialization namespace.

var UserName = @new System.Web.Script.Serialization.JavaScriptSerializer().Seria‌​lize(Request.Query‌​St‌​ring["UserName"]);

The shorter version of this for a string is:

var UserName = "@System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"])";

or overloaded version that wraps the result in double quotes:

var UserName = @System.Web.HttpUtility.JavaScriptStringEncode(Request.Query‌​St‌​ring["UserName"], true);

You need to include quotes for the value.

var UserName = "@(Request.QueryString["UserName"])";

Otherwise the name will come through verbatim in your code and cause the problems you are seeing.

There is no need to protect against an attack vector here as the user can alter the page as they see fit at any time with a user script, and the QueryString is entered by them and only seen as a result by them in this scenario.

If there was a need to scrub the user input, it should be done prior to it actually reaching the view on server side. However, if still concerned about scrubbing output into a view in this type of scenario in general, it would be prudent to include an encode from razor's library.

var sanitizedJsVariable = "@System.Web.HttpUtility.JavaScriptStringEncode(model.VariableFromServer)";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM