Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use both HtmlEncode and JavaScriptStringEncode if inside HTML <script> tag?

I want to render in .NET a string destined for Javascript, say:

<html>
...
<script>
   alert('<%= this.MyStringHere %>');
</script>
</html>

How should I encode MyStringHere? Do I need HttpUtility.HtmlEncode(HttpUtility.JavaScriptStringEncode(unencodedString)) or is just HttpUtility.JavaScriptStringEncode(unencodedString) sufficient? Or are both wrong?

Feel free to mention alternative server tag <% solutions in your answer too, but I'm looking for the code-based solution, the example is a little contrived.

like image 392
Scott Stafford Avatar asked Oct 11 '13 14:10

Scott Stafford


People also ask

When should I use HTMLEncode?

HTMLEncode() Method is used to convert an HTML code to a string. It is used to encode form data and other client request data before using it in the web application.

Where script tag should be placed in HTML?

The <script> tag can be placed in the <head> section of your HTML or in the <body> section, depending on when you want the JavaScript to load. Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.

Why do we need HTMLEncode?

HTML encoding ensures that text will be correctly displayed in the browser, not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as an opening or closing bracket of an HTML tag.

What does JavaScriptStringEncode do?

JavaScriptStringEncode() Method will convert html content to javascript compatible.


1 Answers

You only need to encode the script for JS use, no need to double encode using HTML encoding. Just HTML encoding will not work either because it will not encode \n etc.

<script>
   alert(<%=HttpUtility.JavaScriptStringEncode(this.MyStringHere, true)%>);
   alert("<%=HttpUtility.JavaScriptStringEncode(this.MyStringHere, false)%>");
</script>

Note that JavaScriptStringEncode will not add the double quotes by default - see official docs.

If you have server-side JSON package installed, you could also use that - and it will also work for arrays, dictionaries etc.. Note that it will also add quotes for strings so you do not add them yourself.

You also have to remember that you cannot use <%: text %> syntax since that does the HTML encoding. In MVC Razor views you even have to explicitly disable HTML encoding by using @Html.Raw(Json.Encode(...)).

like image 130
Knaģis Avatar answered Oct 13 '22 11:10

Knaģis