JavaScript encoding transforms data into a representation safe for embedding in JavaScript values. It helps prevent user-supplied content from becoming executable code during an XSS attack. section 29.1
Use JavaScript encoding when inserting data into JavaScript source:
- Inject System.Text.Encodings.Web.JavaScriptEncoder and encode the value before placing it inside a script. section 29.1
- Do not substitute HTML encoding automatically; HTML and JavaScript contexts require different encoders. section 29.1
- Consider passing values through HTML data attributes and reading them with getAttribute instead of constructing JavaScript source directly. section 29.1
Encoding a name inside a script
Use `@encoder.Encode(name)` when assigning a server-side name to a JavaScript variable: `<script>var name = '@encoder.Encode(name)'</script>`. section 29.1
Figure 29.1 How an XSS vulnerability is exploited. An attacker submits malicious content to your app, which is displayed in the browsers of other users. If the app doesn’t encode the content when writing to the page, the input becomes part of the HTML of the page and can run arbitrary JavaScript.
Trace how malicious submitted content reaches other users’ browsers when output is not encoded. section 29.1
