MikiSoft
MikiSoft

Reputation: 1

After clearing document, document.write(ln) won't work?

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!

Upvotes: 0

Views: 96

Answers (2)

Matt Ball
Matt Ball

Reputation: 359826

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);

Upvotes: 3

Blazemonger
Blazemonger

Reputation: 92893

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.

Upvotes: 1

Related Questions