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

标签 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 的元素?问题可能是内容尚未加载吗?我正在使用本地存储,因此所有文件都来自同一个“域”。

感谢您的帮助!

最佳答案

对,您需要等待 iframe 内容加载完毕。使用 jQuery:

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

关于javascript - 为什么我可以访问 iFrame 但不能访问其内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16673325/

相关文章:

javascript - 如何限制网站仅在 iframe 内加载?

javascript - IE iframe 无法正确处理应用程序/json 响应

javascript - Node.js/Express - 如何设置响应字符编码?

c# - 使用 jquery 缩放图像

javascript - 像这个网站一样的 CSS 框阴影

javascript - fadeOut() 回调在淡入淡出完成之前完成

javascript - 表单在 onsubmit 函数完成之前提交

javascript - 将图标与对象相关联

javascript - toTitleCase 函数无法正常工作

reactjs - 如何在React中加载和播放Youtube视频