4

I have what I believe is valid javascript. However I get this: SyntaxError: Unexpected token '<'. Removing any of the script blocks, or changing around the order in the 'a' string fixes the issue. Why is that?

<script>
let a = "<!-- <script>";
</script>
<script></script><!-- --><script></script>

13
  • 3
    What you have is HTML, not javascript. The <script> is not legal javascript. It is a signal to HTML that what comes next is javascript. Commented Jan 30, 2020 at 0:23
  • 3
    @RaymondChen He put it in the HTML block of the snippet editor. Commented Jan 30, 2020 at 0:23
  • May i ask, why you are writing this specific piece of code? Since it looks as if it was purposely written to mess with parsers. Commented Jan 30, 2020 at 0:28
  • 11
    According to the HTML spec: 4.12.1.3 Restrictions for contents of script elements, the character sequence <script is disallowed in embedded script. What you have above is a minor variation of the very first Example in that section. Commented Jan 30, 2020 at 0:28
  • I was able to reproduce it without the last two script blocks, I just needed the comment after the first script. Commented Jan 30, 2020 at 0:29

2 Answers 2

1

You get the same error with:

<script>
document.write('<script>alert("foo")</script>');
</script>

When "parsing" the page the browser sees this as an attempt to nest a <script> block inside another one. e.g.

<script>
  <script>alert("foo")</script>
</script>

The solution is to trick the browser to see something different:

<script>
document.write('<scr' + 'ipt>alert("foo")</scr' + 'ipt>');
</script>

Sign up to request clarification or add additional context in comments.

Comments

0

It seems like opening a <script> tag will make interpreter wait for javascript code until the last </script> is found, except if there is a second <script> opened with javascript inside of it.

Simple <script></script> will be interpreted as part of the JS code, which is invalid.

Might be related to this thread.

enter image description here enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.