通过 window.frames 或 htmliframeelement.contentwindow 获取 iframe 的窗口对象,再使用 contentdocument 访问其 dom 树。前提是主页面与 iframe 同源,否则浏览器会拦截跨域访问。

contentWindow 和 contentDocument 的关系是什么
contentWindow 是 iframe 对应的 Window 实例,而 contentDocument 是该窗口的 document 对象。在标准实现中,iframe.contentDocument === iframe.contentWindow.document。直接操作 contentDocument 即可获取元素,无需经过 window 中转。

<iframe id="myFrame" src="/page.html"></iframe>
<script>
const iframe = document.getElementById('myFrame');
// 等待加载完成
iframe.onload = () => {
const doc = iframe.contentDocument || iframe.contentWindow.document;
const el = doc.querySelector('.target');
console.log(el);
};
</script>
跨域时如何安全地查询 iframe 内元素
如果 iframe 跨域,直接访问 contentDocument 会抛出 SecurityError。此时必须依赖 postMessage API,由 iframe 内部脚本主动将元素信息发送回主页面。主页面监听 message 事件并处理数据。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。

// 主页面
window.addEventListener('message', (event) => {
if (event.origin !== 'https://trusted.com') return;
console.log(event.data); // iframe 发来的数据
});
// iframe 内部
parent.postMessage({ type: 'elementInfo', text: 'Hello' }, '*');
iframe 未加载完成时查询会发生什么
如果在 iframe 的 load 事件触发前尝试访问 contentDocument,可能得到空引用或尚未初始化的 DOM。此时查询结果为 null 或报错。必须确保 iframe 资源加载完毕后再执行 DOM 操作。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










