JavaScript Context Encoding Challenges
What you'll learn: How to safely handle output when embedding data inside JavaScript code, where traditional HTML encoding isn't enough.
When you insert user-controlled data into JavaScript contexts—like inside <script> tags, event handlers (onclick), or dynamically generated code—you face unique encoding challenges that HTML entity encoding alone cannot solve.
Why JavaScript Context Is Different
Unlike HTML content where < becomes <, JavaScript interprets data as code, not text. If you place user input directly into a JavaScript string without proper escaping, attackers can break out of the string context and inject executable code.
Example attack vector:
// Vulnerable: user input inserted into JS string
var username = 'USER_INPUT_HERE';
If USER_INPUT_HERE contains '; alert(document.cookie); //, the code becomes:
var username = ''; alert(document.cookie); //';
The attacker has escaped the string and injected malicious code.
The Triple-Encoding Problem
Data flowing into JavaScript may pass through multiple interpretation layers: HTML parser → JavaScript parser → potentially JSON parser. Each layer requires its own encoding strategy. A quote character might need to be \u0027 for JavaScript, but if embedded in an HTML attribute, you also need HTML encoding first.
Safe Approaches
- JavaScript string escaping: Escape quotes, backslashes, and control characters (
\n,\r, etc.) using backslash notation - Avoid inline event handlers: Use
addEventListener()instead ofonclick="..."attributes - Never build code strings from user input: Don't use
eval()orFunction()constructor with user data - Use JSON.stringify() for structured data (but validate the context where it's placed)
Key Takeaway: JavaScript contexts require specialized escaping beyond HTML encoding; always escape quotes, backslashes, and control characters, and avoid generating dynamic code from user input whenever possible.