frequent
frequent

Reputation: 28483

Why can I access an iFrame but not its contents?

I'm trying to access the contents of an iFrame and I'm getting nowhere.

I have this:

that.findGadget = $.fn.findGadget = function (root) {
    var root = root || this;
    if (root[0].tagName === "IFRAME") {
       root = root[0].contentDocument || root[0].contentWindow.document;
    }
    console.log(root); 

};

I'm calling the function on the iFrame itself like so:

// options is my configuration object with id/src/...
var newHTML = document.createElement("iframe");
newHTML.setAttribute("src", options.src);
newHTML.setAttribute("frameborder", 0);
newHTML.setAttribute("data-id", options.id);
// add iFrame to page
// options.parent is a $(element)
newParentElement = options.parent.parent()[0];
options.parent.replaceWith( newHTML );

// select
var newRootElement = newParentElement.querySelectorAll(
    '[data-id="'+options.id+'"]'
  );
// calling on $('iframe')
$( newRootElement[0] ).findGadget();
...

My if statement inside findGadget works allright, so root is set to document of the iFrame. However I'm stuck from there, because everything else I'm trying:

root.body
root.body.innerHTML
$(root).find('div');
$('iframe').contents();

is undefined or an empty selector.

Question:
How do I correctly access the elements of an iFrame? Could the problem be that the contents haven't been loaded? I'm working on localstorage, so all files are from the same "domain".

Thanks for help!

Upvotes: 0

Views: 199

Answers (2)

Christophe
Christophe

Reputation: 28114

Right, you need to wait until the iframe content has loaded. Using jQuery:

$('iframe').load(function () {                        
    // access the iframe content
});

Upvotes: 1

rocky
rocky

Reputation: 7696

Consider following:

1) I'd recommend to fire the findGadget() function when iframe is loaded. You can achieve this by calling it from within the iframe's page itself or by putting whole $(newRootElement[0] ).findGadget(); into

$(newRootElement[0]).ready(function (){
    // here
});

2) I recommend using only contentWindow as it's fully compatible with all browsers (tested).

Upvotes: 1

Related Questions