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

2020-02-09 09:37发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

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>