EXERCISE 2 — Why HTML encoding fails inside a The developer "escapes" the value with HTML entity encoding, thinking it's safe. WHY HTML ENTITY ENCODING DOESN'T PROTECT THIS: - HTML entity encoding (turning " into ", < into <, etc.) is decoded by the HTML PARSER. But inside a The HTML parser scans for the literal sequence "" REGARDLESS of JavaScript string quoting. So even inside var name = "..." the ends the script element, and the following from closing the block. - Other breakouts: a bare " (closes the JS string) then ; alert(1); // (HTML encoding of < > & wouldn't touch the " the attacker needs); also backslashes and Unicode line separators (U+2028/U+2029) can break JS. THE RECOMMENDED APPROACH (and why it's safer): - DON'T template untrusted data directly into JavaScript. Instead, put the value into the DOM as DATA and read it from JS:
Now the value lives in an HTML attribute (encode it for THAT context, quotes included) and JS reads it as an inert string via dataset -- it's never parsed as code. - Alternative: emit it as JSON in a script of type application/json, or via a properly JSON-encoded-AND-HTML-encoded blob, and JSON.parse it. - WHY SAFER: the data never enters the JS grammar as source text, so there's no JS string to break out of and no hazard handled incorrectly. You reduce the problem to a single, well-understood HTML-attribute (or JSON) encoding instead of fragile JS-string escaping. - If you absolutely must inline into JS, use a strict JS-string encoder (hex-escape every non-alphanumeric: \xHH, and also escape / to avoid ) -- but avoiding the context is the real fix. ONE-LINE TAKEAWAY: The JS parser ignores HTML entities, and closes the block from inside any string -- so HTML-encoding can't secure a JS context. Keep untrusted data OUT of JavaScript; pass it as DOM data and read it.