【问题标题】:fail to access child iframe content as expected无法按预期访问子 iframe 内容
【发布时间】:2015-04-03 15:57:51
【问题描述】:

尝试一个关于 标签使用的非常简单的案例,结果让我很困惑。希望任何人都可以帮助我。我在等,谢谢。

基本上,我有两个简单的页面,top.htmliframe.html,它们是同一个域,iframe.htmltop.html标签的"src"

当我尝试访问 top.html 中的 内容时,虽然结果很奇怪,但所有元素都是空白的。

top.html 中的控制台日志非常奇怪,iframe.html 中的控制台日志是正常的。

//加载页面后来自 top.html 的控制台日志

outer log: NodeList[head, body]  ---  top.html (line 6)
outer log: 2                     ---  top.html (line 7)
outer log: ""                    ---  top.html (line 8)

//

中点击按钮后来自 iram.html 的控制台日志
inner log: NodeList[head, <TextNode textContent="\n">, body]  ---  iframe.html (line 6)
inner log: 3                                                  ---  iframe.html (line 7)
inner log: "Child iFrame"                                     ---  iframe.html (line 8)

// top.html

<html>
<body>
<iframe id="fid" src="/iframe.html"></iframe>
<script type="text/javascript">
  var i = document.getElementById("fid");
  console.log("outer log: %o", i.contentDocument.documentElement.childNodes);
  console.log("outer log: %o", i.contentDocument.documentElement.childNodes.length);
  console.log("outer log: %o", i.contentDocument.documentElement.childNodes[1].innerHTML);
</script>
</body>
</html>

// iframe.html

<html>
<head>
<script type="text/javascript">
function show () {
  var x = window.top.document.getElementById("fid");
  console.log("inner log: %o", x.contentDocument.documentElement.childNodes);
  console.log("inner log: %o", x.contentDocument.documentElement.childNodes.length);
  console.log("inner log: %o", x.contentDocument.documentElement.childNodes[2].childNodes[1].innerHTML);
}
</script>
</head>
<body>
<p>Child iFrame</p>
<input type="button" onclick="show()" value="Show Button" />
</body>
</html>

谢谢

【问题讨论】:

  • “结果太奇怪了,所有元素都是空白”——这可能是因为你没有等待 iframe 内容完全加载……
  • 谢谢CBroe,叹息...真可惜,我被困了几分钟...

标签: dom iframe same-origin-policy


【解决方案1】:

在window.onload中添加测试,结果符合预期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多