Microsoft.Security.Application.Encoder.JavaScriptEncode()
is only intended to encode untrusted data that will be used in a JavaScript string literal. The optional second argument, boolean emitQuotes
, specifies whether quotation marks will be added at either end the output string (the default is true). So for example, here are two ways the method might be used in ASP.NET WebForms:
<script>
<% string nameEnteredByUser = "alert('I am a hacker');"; %>
var name = <%= Microsoft.Security.Application.Encoder
.JavaScriptEncode(nameEnteredByUser) %>;
var nameWithMessage = '<%= Microsoft.Security.Application.Encoder
.JavaScriptEncode(nameEnteredByUser, false) %>' + ' is a very nice name.';
console.log(name); //alert('I am a hacker');
console.log(nameWithMessage); //alert('I am a hacker'); is a very nice name.
</script>