liveBook · Manning

JavaScriptEncoder

As explained in ASP.NET Core in Action, 3e

JavaScriptEncoder is a .NET encoder type that converts text into a representation safe for use in JavaScript contexts.

JavaScriptEncoder converts text into a representation safe for insertion into JavaScript. It prevents JavaScript contexts from receiving HTML encoding, which can display characters such as quotation marks incorrectly. section 29.1

Encoding a value in Razor

Inject the encoder and call Encode() before inserting a value into a script: @inject System.Text.Encodings.Web.JavaScriptEncoder encoder; <script>var name = '@encoder.Encode(name)'</script>. A quotation mark becomes the safe Unicode sequence \u0022. section 29.1

Prefer writing values into HTML attributes and reading them with JavaScript instead of embedding values directly in scripts. This usually removes the need for JavaScriptEncoder and keeps encoding aligned with the output context. section 29.1

Listing 29.1 Passing values to JavaScript by writing them to HTML attributes
<div id="data" data-name="@name"></div>
<script>                                        #1
var ele = document.getElementById('data');      #2
var name = ele.getAttribute('data-name');       #3
</script>

Shows the recommended attribute-based flow: place the value in data-name, retrieve the element, and read the attribute from JavaScript. section 29.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Demonstrates injection and Encode(), then defers direct script insertion in favor of HTML attributes.
Examples
Uses a quoted Schwarzenegger name and an attribute-based data-name element.
What it assumes
Assumes basic Razor and JavaScript syntax while demonstrating the encoding distinction directly.
What you can do after
Apply JavaScriptEncoder through dependency injection and Encode() when direct script insertion is unavoidable.
How it connects
Connects JavaScript encoding with XSS, Razor templates, HTML encoding, HTML attributes, and JavaScript.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.