0

I am trying to attach a <script> node with the following code

<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
  $('body').append('<script>alert(\'foo\');</script>');
</script>
</body>
</html>

I expect the code

alert('foo');

to be added an executed, but actually, the following string is added

');

What is happening here?

sawa
  • 165,429
  • 45
  • 277
  • 381
  • Because it ends the script tag earlier: http://stackoverflow.com/a/236106/142985 – Nathan Apr 24 '14 at 07:00
  • possible duplicate of [Can I create script tag by jQuery?](http://stackoverflow.com/questions/1199676/can-i-create-script-tag-by-jquery) – CodingIntrigue Apr 24 '14 at 07:11

2 Answers2

4

You have to properly escape the slash character here and use doublequotes for foo:

<html>
  <body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script>
      $('body').append('<script>alert("foo");<\/script>');
    </script>
  </body>
</html>
kaytrance
  • 2,657
  • 4
  • 30
  • 49
3

You have to break </script> inside the string or it will considered as the end tag for <script>.

  $('body').append('<script>alert(\'foo\');</scr'+'ipt>');
xdazz
  • 158,678
  • 38
  • 247
  • 274