Why does adding </script> in a comment break the parser? [duplicate]
Solution 1:
This happens because HTML parser as defined by W3C is totally separated from the JavaScript parser. After the <script>
tag it looks for the closing </script>
, regardless that it's inside comments or strings, because it treats JS code as normal text.
Solution 2:
The HTML parser does not parse JavaScript. It only parses HTML elements, denotated by <tag>
and </tag>
tags. It has no idea that something is a JavaScript comment. When it sees the </script>
closing tag, it assumes the script element is being closed. The same would occur in whatever context the string </script>
appeared; for instance, console.log("</script>")
would yield the same behavior.
This is a pretty good reason not to embed scripts inside HTML, but rather to include them externally.
Solution 3:
You can HTML-escape embedded JavaScript code
<script type="text/javascript">
<!--
function Foo(){
// </script>
alert("bar");
};
Foo();
//-->
</script>
Thus, the whole JavaScript code is treated as HTML comment by HTML parser and HTML comment lines are ignored by JavaScript interpreter.