JavaScript: 如何从父级 HTML 获取 iframe 节点内容

使用 JavaScript 中的 contentWindow 属性可以轻松获取 iframe 的 Window 对象,并通过 parent 属性访问父级页面的 Window 对象。这样,你就可以在父级页面中访问和操作 iframe 中的节点了。

示例代码

// 获取 iframe 元素
var iframe = document.getElementById('my-iframe');
// 获取 iframe 的 Window 对象
var iframeWindow = iframe.contentWindow;
// 获取父级页面的 Window 对象
var parentWindow = window.parent;
// 在父级页面中访问 iframe 中的节点
var iframeNode = iframeWindow.document.getElementById('my-iframe-node');

解释:

  1. document.getElementById('my-iframe'):获取名为 'my-iframe' 的 iframe 元素。
  2. iframe.contentWindow:获取 iframe 的 Window 对象。
  3. window.parent:获取父级页面的 Window 对象。
  4. iframeWindow.document.getElementById('my-iframe-node'):通过 iframe 的 Window 对象访问其内部的 DOM 节点,并获取名为 'my-iframe-node' 的节点。

通过这些步骤,你就可以在父级 HTML 中轻松访问和操作 iframe 中的节点内容了。

JavaScript: 如何从父级 HTML 获取 iframe 节点内容

原文地址: https://www.cveoy.top/t/topic/oLeR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录