JavaScript string literals and </script> tags don’t mix

What do you think happens if you try to open up a web page containing the following HTML and JavaScript? Give it a try – the results may surprise you!


It turns out that web browsers are very indiscriminate when parsing closing script tags. The browser will find the </script> tag, even though it’s inside of a string literal in a <script> tag, and consider it to be the end of the script. The result is a few leftover characters and an unmatched </script> tag, which the browser chokes on.


Chrome throws an “Uncaught SyntaxError: Unexpected token ILLEGAL” error.

This was definitely not theĀ behaviorĀ I was expecting. After thinking about it, though, it makes perfect sense. The HTML parser doesn’t know anything about the contents of the script. It doesn’t understand that quoted strings should be treated differently. And why should it? The stuff inside the script tags could be anything, in theory.

Sure, this isn’t iOS-specific, but I thought it was interesting enough to be worth sharing anyway.

Leave a Reply

Your email address will not be published. Required fields are marked *