Iframes and jQuery - Working with an embedded iframe

IFrames, while they can be bad for accessibility (i.e. bookmarking), can also be very handy.

What I found was that working with iframes proved troublesome. I initially thought it would be as simple as this:

JavaScript
$( function() {
 $("#myiframe").load( function(){
  alert("Number of anchors: " + this.$("a").size());
  alert("Document title: " + this.document.title);
 });
});
HTML
<iframe src="myiframe.html" id="myiframe" name="myiframe"></iframe>

However, this caused several errors: this.document has no properties (i.e. this.document is undefined) and this.$ is not a function, so I had to find another way. After some trial and error in Internet Explorer and Firebug in Firefox, I found a way (which also works in Opera 9 as well, unsure about Safari though).

$( function() {
   var myiframe = $($.browser.msie ? frames["myiframe"] : "#myiframe");
   // doesn't work in Opera < 9
   myiframe.load( function() {
       var w = this.contentWindow;
       if(!w) w = myiframe[0]; // IE
       alert("Number of anchors: " + w.$("a").size());
       alert("Document title: " + w.document.title);
   })
})

Several things to note:

  • In Internet Explorer, if you navigate to a different page in the iframe, the load event is not fired again.
  • The iframe needs the id and name attributes to both be present and the same.
  • The iframe page also needs to include jQuery

Comments

Anonymous said…
Using jQuery 1.2.3 and Firefox 2, I encounter an unfortunate exception of

[Exception... "'Permission denied to get property Window.jQuery' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x8057001e (NS_ERROR_XPC_JS_THREW_STRING)" location: "<unknown>" data: no]

when attempting to execute merely


myiframe.load( function() {
var w = this.contentWindow;
console.log("Number of anchors: " + w.jQuery("a").size());
})
Anonymous said…
Yea, I don't believe this method works anymore. I'm getting the same issue using jquery 1.2.6 and FF 3 with firebug debugging.
Anonymous said…
added a line

w = w.document;

after


if(!w) w = myiframe[0]; // IE

Firefox 3.0.9
jQuery 1.3.2

works like a charm in FF
not so god in IE (as in... not at all)
Anonymous said…
Understand that iFrame structure is unavailable, if the source of iFrame is called from external server...
Anonymous said…
Initailly i was using this piece of jquery code and it was working fine with in Firefox. But i encounter problem with IE.
$('#my_iframe').load( function(){

Now with this line of code
var myiframe = $($.browser.msie ? frames["my_iframe"] : "#my_iframe");

it work in both Firefix and IE.

Thankx a lot.

Popular posts from this blog

Link: HTML Agility Pack (.NET)

Basic Excel Spreadsheet Generation (ASP/ASP.NET)

ASP.NET: Binding alphabet to dropdown list