为什么我可以访问iFrame但不能访问其内容?

时间:2013-05-21 15:05:41

标签: javascript jquery iframe

我正在尝试访问iFrame的内容而我无处可去。

我有这个:

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

};

我正在调用iFrame本身的函数:

// 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();
...

findGadget中的我的if语句可以正常工作,因此root设置为iFrame的document。但是我被困在那里,因为我正在尝试的其他一切:

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

未定义或为空选择器。

问题
如何正确访问iFrame的元素?问题可能是内容尚未加载?我正在使用localstorage,因此所有文件都来自同一个“域”。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

请考虑以下事项:

1)我建议在加载iframe时触发findGadget()函数。您可以通过在iframe的页面内调用它或将整个$(newRootElement[0] ).findGadget();放入

来实现此目的
$(newRootElement[0]).ready(function (){
    // here
});

2)我建议仅使用contentWindow,因为它与所有浏览器(已测试)完全兼容。

答案 1 :(得分:1)

是的,你需要等到iframe内容加载完毕。使用jQuery:

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