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
[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());
})
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)
$('#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.