1

I'm writing some Javascript code for an ASP.net page.

I have the string "foo" assigned to a string variable myString.

I would like to assign the value of myString to a JavaScript variable, so I write in my ASP.net code:

<script type='txt/javascript' language='javascript'>
    var stringFromDotNet = '<%=myString%>';
</script>

This works fine as long as myString does not contain quotation marks or line-breaks, but as as soon as I try to assign something with quotation marks or line-breaks, all hell breaks loose and my code doesn't work. As a matter of fact, I can see that this code is vulnerable to all sort of injection attacks.

So... What can I do get the value of myString assigned to a variable in JavaScript?

Update: I've tried creating a page with just an ASP:Hidden field. It looks like the values inside are html encoded.

3 Answers 3

5

You could use JavaScriptSerializer and that's guaranteed to be safe against XSS:

<script type="text/javascript">
    var stringFromDotNet = <%= new JavaScriptSerializer().Serialize(myString) %>;
</script>

This approach also allows you to pass complex objects and not just plain strings:

<script type="text/javascript">
    var complexObjectFromDotNet = <%= new JavaScriptSerializer().Serialize(new { id = 123, name = "foo\"' <bar>" }) %>;
    alert(complexObjectFromDotNet.name);
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

I think this may be the answer are looking for: http://www.velocityreviews.com/forums/t70655-escape-function-in-asp-net.html#edit352659. Basically, encode the value on the server side and unencode it with JavaScript:

var stringFromDotNet = decodeURI(<%=Server.URLEncode(myString)%>);

This will ensure that quotes and other dangerous characters won't break your script, or open up attack vectors.

Comments

0

You could either assign the js variable using double quotes like so

var stringFromDotNet = "<%=myString%>";

Or you could escape the single quotes and replace line breaks with literal "\r\n" in your string in the server side.

2 Comments

That doesn't work because then my user's can't use double-quotes and I am still wide open to attack.
You'll have to escape the quotes. If you're assigning the js variable using double quotes, you'll have to escape the double quotes in your string. You're user are not impacted. You have to escape the string at the time of assigning the value to myString.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.