Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly do I have to escape inside a `script` element?

What parts of JavaScript code do I have to escape inside a script element in a HTML page? Is <>& enough or too much?

[EDIT] This is related to this bug: http://code.google.com/p/rendersnake/issues/detail?id=15#c6 comment #6

like image 339
Aaron Digulla Avatar asked Aug 02 '11 07:08

Aaron Digulla


1 Answers

In HTML (and XHTML if you're an evil person that sends your XHTML pages as text/html), script tags are #CDATA, and therefore, the only thing that you shouldn't have in the content is </script>, as that is all that the parser looks for to signal the end of the tag. Don't escape anything; just make sure you don't have </script> in the tag content. For example, if you have a string with a closing script tag, split it up:

var a = '</scr' + 'ipt>';

In XHTML, sent as application/xhtml+xml, script tags are #PCDATA, and therefore, escaping < and & is necessary, unless you can use a <![CDATA[ ... ]]> block to change to #CDATA parsing mode, but in that case, remember that you can't have ]]> in your tag content.

like image 92
Delan Azabani Avatar answered Sep 18 '22 05:09

Delan Azabani