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

耗尽温柔 提交于 2019-11-29 01:45:31

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!