What parts of JavaScript code do I have to escape inside a script
element in a HTML page? Is <&g开发者_如何学Got;&
enough or too much?
[EDIT] This is related to this bug: http://code.google.com/p/rendersnake/issues/detail?id=15#c6 comment #6
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.
Generally, the only thing I escape is the /
in closing tags. Thus:
var msg = "<p>Do you <em>really<\/em> think so, Miss Worthington?<\/p>";
For the rest, I rely on commenting out the entire thing:
<script>
<!--
var msg = "<p>Do you <em>really<\/em> think so, Miss Worthington?<\/p>";
-->
</script>
The comment takes care of the HTML opening tags.
Escaped <, > and & does not work with many browsers. It is good an enough if you put everything inside a CDATA section. Please note that the CDATA section itself will have to be in a JavaScript comment, for this to work with all browsers.
<script>
// <![CDATA[
script here
// ]]>
</script>
精彩评论