akshat
akshat

Reputation:

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?

Upvotes: 3

Views: 1805

Answers (6)

dimarzionist
dimarzionist

Reputation: 18687

Workaround is to programmatically add <script> blocks to head DOM element in JavaScript at Callback function or call eval() method. It's only way you can make this work in IE 6.

Upvotes: 1

Ollie Saunders
Ollie Saunders

Reputation: 8057

You could use an onload attribute in the body tag (<body onload="jsWrittenLoaded()">).

Upvotes: 0

Ateş G&#246;ral
Ateş G&#246;ral

Reputation: 140032

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

Upvotes: 1

cllpse
cllpse

Reputation: 21727

Eval and/or executing scripts dynamically is bad practice. Very bad practice. Very, very, very bad practice. I can't stress enough, how bad practice it is.

AKA.: Sounds like bad design. What problem are you trying to solve again?

Upvotes: 0

Armin Ronacher
Armin Ronacher

Reputation: 32533

In short: You can't really do that. However JavaScript libraries such as jQuery provide functionality to do exactly that. If you depend on that, give jQuery a try.

Upvotes: 0

dimarzionist
dimarzionist

Reputation: 18687

Another possible alternative is to use JSON, dynamically adding scripts references which will be automatically processed by browser.

Cheers.

Upvotes: 0

Related Questions