0

as in title says I have a problem, here is example:

...    
<script>
document.body.innerHTML = "";
document.write("<scr"+"ipt>alert(1);<\/scr"+"ipt>");
</script>

After clearing document, I want to write in it some JS code (and I want to be executed of course). I have tried other methods but it seems that they won't work (and I have browser Firefox 6.0).

Does anyone know solution or working alternative for this problem? Thanks in advance!

  • 1
    Where is the script positioned? If it is in the `head` it does not work because `document.body` is `null`. The `body` of the document was not parsed yet. – Felix Kling Aug 30 '11 at 13:13

2 Answers2

3

Don't use document.write(). Just don't. (See Why is document.write considered a "bad practice"?)


Try this:

var text = 'alert(1);',
    script = document.createElement('script');
script.appendChild(document.createTextNode(text));
document.head.appendChild(script);
Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1

document.write only works before the DOM is loaded; document.body.innerHTML only works after.

Try using document.body.appendChild to append a new text node instead.

Blazemonger
  • 90,923
  • 26
  • 142
  • 180