Chris@0: # Escaping Javascript Chris@0: Chris@0: Javascript string literals in HTML are subject to significant restrictions due Chris@0: to the potential for unquoted attributes and uncertainty as to whether Chris@0: Javascript will be viewed as being `CDATA` or `PCDATA` by the browser. To Chris@0: eliminate any possible XSS vulnerabilities, Javascript escaping for HTML extends Chris@0: the escaping rules of both ECMAScript and JSON to include any potentially Chris@0: dangerous character. Very similar to HTML attribute value escaping, this means Chris@0: escaping everything except basic alphanumeric characters and the comma, period, Chris@0: and underscore characters as hexadecimal or unicode escapes. Chris@0: Chris@0: Javascript escaping applies to all literal strings and digits. It is not Chris@0: possible to safely escape other Javascript markup. Chris@0: Chris@0: To escape data in the **Javascript context**, use `Zend\Escaper\Escaper`'s Chris@0: `escapeJs()` method. An extended set of characters are escaped beyond Chris@0: ECMAScript's rules for Javascript literal string escaping in order to prevent Chris@0: misinterpretation of Javascript as HTML leading to the injection of special Chris@0: characters and entities. Chris@0: Chris@0: ## Example of Bad Javascript Escaping Chris@0: Chris@0: An example of incorrect Javascript escaping: Chris@0: Chris@0: ```php Chris@0: Chris@0: Chris@0: Chris@0: Chris@0:
Chris@0:json_encode() is not good for escaping javascript!
Chris@0: Chris@0: Chris@0: ``` Chris@0: Chris@0: The above example will show an alert popup box as soon as the page is loaded, Chris@0: because the data is not properly escaped for the Javascript context. Chris@0: Chris@0: ## Example of Good Javascript Escaping Chris@0: Chris@0: By using the `escapeJs()` method in the Javascript context, such attacks can be Chris@0: prevented: Chris@0: Chris@0: ```php Chris@0: Chris@0: Chris@0: escapeJs($input); Chris@0: ?> Chris@0: Chris@0: Chris@0:Zend\Escaper\Escaper::escapeJs() is good for escaping javascript!
Chris@0: Chris@0: Chris@0: ``` Chris@0: Chris@0: In the above example, the Javascript parser will most likely report a Chris@0: `SyntaxError`, but at least the targeted application remains safe from such Chris@0: attacks.