within a JavaScript string in a
Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

</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?

like image 422
jookos Avatar asked Dec 11 '22 07:12

jookos


1 Answers

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.

like image 86
zzzzBov Avatar answered Jan 01 '23 07:01

zzzzBov