Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get JavaScript created with document.write() to execute?

I have a multi-frame layout. One of the frames contains a form, which I am submitting through XMLHttpRequest. Now when I use document.write() to rewrite the frame with the form, and the new page I am adding contains any javascript then the javascript is not exectuted in IE6?

For example:

document.write("<html><head><script>alert(1);</script></head><body>test</body></html>");

In the above case the page content is replaced with test but the alert() isn't executed. This works fine in Firefox.

What is a workaround to the above problem?


1 Answers

Instead of having the JS code out in the open, enclose it in a function (let's call it "doIt"). Your frame window (let's say it's name is "formFrame") has a parent window (even if it's not visible) in which you can execute JS code. Do the actual frame rewrite operation in that scope:

window.parent.rewriteFormFrame(theHtml);

Where rewriteFormFrame function in the parent window looks something like this:

function rewriteFormFrame(html) {
    formFrame.document.body.innerHTML = html;
    formFrame.doIt();
}
like image 122
Ates Goral Avatar answered Dec 30 '25 17:12

Ates Goral