skip to Main Content

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


  1. You need to escape the / character within </script> otherwise it will be treated as a closing tag.

    <script>    
        const str = '<script>alert(0)</script>' // notice /
        console.log(str)
    </script>
    
    Login or Signup to reply.
  2. 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:

     </script>
    

    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:

    <script src="http:example.com/myscript.js"></script>
    

    or in non HTML environments such as under nodejs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search