Thursday, January 25, 2007

Scripting IFrames in IE and Firefox

Update: Found out Safari requires iframeEl.contentWindow, iframeEl.contentDocument.defaultView doesn't work (or, at least, it doesn't work any more). Turns out that this works for Firefox as well. I've left the other branch for backwards compatibility and also because it is more standard.

Here's how to get a reference to an iframe with JavaScript, in Firefox and IE, IE and Safari:


var iframeEl = document.getElementById("iframeId");
var iframeDoc = iframeEl.contentDocument
var iframeWin;
if (iframeDoc) { // Firefox
iframeWin = iframeDoc.defaultView
} else { // IE
iframeWin = iframeEl.contentWindow
}
if (iframeEl.contentWindow) { // IE and Safari require, but works for Firefox too
iframeWin = iframeEl.contentWindow;
} else if (iframeEl.contentDocument) { // Works for Firefox, DOM level 2 standard
iframeWin = iframeEl.contentDocument.defaultView;
}

And then you can use iframeWin to get access to JavaScript objects and the DOM of the iframe.

Also, I learned that getElementById() in IE (version 7 tested) picks up elements by name attribute as well, so names and ids need to be unique for all elements on a page for IE.

2 comments:

Daniel said...

This saved my bacon this week. Thanks a ton!

Doug said...

Thanks so much for posting this. I have spent many hours trying to figure this out. This technique works great on IE, FF and Chrome as of April 2011.