JavaScript eval in iframes

Posted by Tim Down on January 22nd, 2007

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.

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



Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Interesting, recently I had a situation in which I needed to replace all onclick atttributes as well as script tags, replace some pop ups code for something else.

Thep problem with reevaluating, because we use iframes for the content, and the reevaluatinf is happenining in the top window, it was reevaluating at the top window instead, and things got complicated, so I decided to evaulate directly in the iframe.

This is a neat solution to my problem :D

Thanks