In the course of developing a new version of log4javascript, I was adding a command line feature that required the ability to evaluate and execute code in an iframe from within the main window. Fine, I thought, I’ll just call eval on the iframe window object. Which predictably worked fine in Firefox and Opera 8+, but did nothing in IE, which seemed to be missing the eval method on the iframe.

Script Execution

After some googling I came across a mention of the IE-specific execScript method of window objects, which looked like it might do the job. However, I got my implementation slightly wrong but then noticed that after the first (wrong) call to execScript my original code was working! It turns out that calling execScript once on a window object causes the eval method magically to appear. This is true of every version of IE I’ve tested in Windows (7, 6, 5.5, 5, even 4); I haven’t tried IE on the Mac, or Safari, yet.

So I have a nice easy workaround in IE that still works in other browsers:


function evalIframe(iframe, command) {
if (!iframe.eval && iframe.execScript) {
iframe.execScript("null");
}
iframe.eval(command);
}