在 JavaScript 中访问 iframe 元素

IT技术 javascript iframe
2021-01-12 02:31:22

我有一个网页,其中 iframe 中有一个 textarea。我需要使用 JavaScript 从它的子页面读取这个 textarea 的值。

目前通过window.parent.getelementbyID().value在 JavaScript 中使用,我能够获取父页面中除 iframe 中的 textarea 之外的所有控件的值。

任何人都可以给我任何指示来解决这个问题吗?

6个回答

如果您的 iframe 与您的父页面在同一个域中,您可以使用window.frames集合访问元素

// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on window.frames['myIFrame'].document like you are working on
// normal document object in JS
window.frames['myIFrame'].document.getElementById('myIFrameElemId')

如果您的 iframe 不在同一个域中,出于安全原因,浏览器应阻止此类访问。

非常感谢您的建议。但问题是我的父页面中的 frame id n frame name 在运行时发生了变化,因此我们不能使用 frame id/frame name 作为参考。拉耶尔还有其他办法吗?...
2021-03-12 02:31:22
两个父 n 子页面在同一个域中。
2021-03-13 02:31:22
.contentDocument而不是document为我工作
2021-03-14 02:31:22
如果您的网站上只有一个 iframe,您可以尝试使用document,frames[0].document. 如果还有更多,您需要将索引更改为其他值。
2021-03-16 02:31:22
document.frames不再有效。使用window.frames来代替。
2021-03-29 02:31:22

window.frames['myIFrame'].document.getElementById('myIFrameElemId')

不适合我,但我找到了另一个解决方案。利用:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

我在 Firefox 和 Chrome 上检查过。

不要看别的,这是实际的答案,太棒了
2021-03-25 02:31:22
即使网页都处于脱机状态,我仍然遇到安全错误。
2021-04-03 02:31:22

您应该window从而不是访问框架document

window.frames['myIFrame'].document.getElementById('myIFrameElemId')

确保您的 iframe已加载没有 jQuery 的旧但可靠的方法:

<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>

<script>
function access() {
   var iframe = document.getElementById("iframe");
   var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
   console.log(innerDoc.body);
}
</script>

这段代码对我有用:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId');