I do have a code that I thought should just write plaint text <script>alert(0)</script>
into console
<script>
const str = '<script>alert(0)</script>'
console.log(str)
</script>
why it does not prints
<script>alert(0)</script>
into console
but ' console.log(str)
in the body
jsfiddle live
https://jsfiddle.net/1b5js8fy/
2
Answers
You need to escape the
/
character within</script>
otherwise it will be treated as a closing tag.The HTML parser starts a script element when it encounters an opening
<script>
tag, and passes all HTML source up to the next</script>
, along with attribute values of the opening tag to the JavaScript engine to create a script object.If the JavaScript code needs to contain
</script>
it must be written differently to avoid being detected by the HTML parser.A typical solution is to backslash the forward slash in code strings:
where the backslash escape
/
sequence is resolved to a single forward slash without being treated as the HTML end script tag.Note the issue does not relate to environments which are not being parsed by the HTML parser first, such as when including external scripts using
scr
attribute on the opening tag of a script element pair in HTML:or in non HTML environments such as under nodejs.