Course contentsShow
← Web Development
Lesson 2898 of 2,98252. Frontend SecurityFree lesson

JavaScript Context Encoding

Safely handling user data within script tags and inline event handlers.

JavaScript Context Encoding

You'll learn how to safely embed user data inside <script> tags and inline event handlers without creating XSS vulnerabilities.

The Core Problem

When you insert user-provided data directly into JavaScript code—whether inside a <script> block or an inline event handler like onclick—attackers can break out of the string context and execute arbitrary code. HTML encoding alone won't protect you here because the browser parses JavaScript differently than HTML.

Why HTML Encoding Isn't Enough

Imagine you HTML-encode user input and place it in a script:

<script>
  var name = "O&apos;Reilly"; // HTML-encoded apostrophe
</script>

The browser reads the HTML first (decoding &apos; to '), then parses the JavaScript, seeing var name = "O'Reilly";—which breaks your string! An attacker could submit "; alert(1); // and execute code.

JavaScript Context Encoding Rules

When embedding data in JavaScript contexts, you must:

  1. Escape backslashes (\ → \\)
  2. Escape quotes (" → \", ' → \')
  3. Escape newlines (\n → \\n)
  4. Escape other control characters (tabs, carriage returns, etc.)
<script>
  var userInput = "User typed: \"Hello\\nWorld\""; // Safe
</script>

<button onclick="alert('Safe: \\'quoted\\' text')">Click</button>

Additional Safeguards

Even with proper escaping, avoid building JavaScript dynamically from user input when possible. Prefer passing data through HTML attributes and reading them with JavaScript, or use JSON encoding for complex data structures.

Key Takeaway:
JavaScript context encoding requires escaping backslashes, quotes, and control characters—HTML encoding alone won't prevent XSS in script tags or event handlers.