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

后端 未结 3 1346
轻奢々
轻奢々 2020-12-16 00:28

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

[EDI

相关标签:
3条回答
  • 2020-12-16 01:11

    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.

    0 讨论(0)
  • 2020-12-16 01:25

    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.

    0 讨论(0)
  • 2020-12-16 01:26

    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>
    
    0 讨论(0)
提交回复
热议问题