简体   繁体   中英

</script> within a JavaScript string in a <script> tag

I have an app that can generate all sorts of things into the JavaScript strings put on the page. I thought all the escaping were ok, but then I came across a weird problem that I couldn't really find a reason for:

Shouldn't this be legal in an html page:

<script type="text/javascript">
    alert("hello </script>");
</script>

'Legal' meaning that it would produce an alert with hello </script> .

Apparently both moz and chrome, on my box at least, cuts the scripting off after the </script> part of the alert string, producing no alert and a messy output. Has anyone run into this, is this a browser bug?

The HTML parses it as:

<script type="text/javascript">
    alert("hello 
</script>
");
</script>

With the first occurrence of </script> closing the open <script> element. The common way of avoiding this issue is by including a \\ before the / character in the string:

<script type="text/javascript">
    alert("hello <\/script>");
</script>

This works because the \\ escape character will prevent the browser from recognizing <\\/script> as an end tag. Normally \\ is used as an escape sequence in JavaScript strings, but as there's no \\/ sequence, the escape character is ignored and the string evaluates as '</script'> .

This issue can generally be avoided if you follow the good practice of keeping all of your javascript in external .js files. That said, it's common to see this sort of escaping used for local script fallbacks for unresponsive CDNs .

<script type="text/javascript">
    alert('hello <'+'/script>');
</script>

<script type="text/javascript">
    alert('hello <\/script>');
</script>

You should do like

<script type="text/javascript">
// <![CDATA[
    alert('hello </script>');
// ]]>
</script>

To prevent the parsing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM