4

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?

Uri Agassi
37.5k16 gold badges83 silver badges96 bronze badges
asked Mar 18, 2014 at 19:10
3

3 Answers 3

10

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.

answered Mar 18, 2014 at 19:13
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for pointing out that html and script parsing work at different layers.
3
<script type="text/javascript">
 alert('hello <'+'/script>');
</script>
<script type="text/javascript">
 alert('hello <\/script>');
</script>
answered Mar 18, 2014 at 19:13

1 Comment

Explain something that what you did here, don't just post your codes, will help people who don't understand what you did over here...
0

You should do like

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

To prevent the parsing.

answered Mar 18, 2014 at 19:14

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.