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
  • [You should accept Matt's answer by clicking the hollow check](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – SLaks Sep 02 '11 at 18:00

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
  • 332,322
  • 92
  • 617
  • 683
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
  • 82,329
  • 24
  • 132
  • 176