Why does adding </script> in a comment break the parser?
JavascriptHtmlJavascript Problem Overview
Why does adding </script>
in a comment break the parser? Is this a bug or is there something in the documentation I've overlooked?
I've tested this in Chrome, Firefox, Opera, Internet Explorer and they all produce the same result.
Single-line comment:
function Foo(){
// </script>
alert("bar");
};
Foo();
Multi-line comment:
function Foo(){
/*
</script>
*/
alert("bar");
};
Foo();
Javascript Solutions
Solution 1 - Javascript
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 - Javascript
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 - Javascript
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.
Solution 4 - Javascript
An easier workaround would be embedding comments:
function Foo(){
//<!-- </script> -->
alert("bar");
};
Foo();
It will comment the line for javascript AND for html.