JavaScript操作iframe需先获取DOM引用,同源时用contentWindow/contentDocument直接操作,跨域时必须用postMessage通信,并校验origin确保安全。

JavaScript 操作 iframe 的核心在于获取 iframe 的 DOM 引用,并在满足同源策略的前提下访问其内容或触发通信。跨域时不能直接操作 document,需改用 postMessage 进行安全通信。
获取 iframe 的 DOM 引用
通过 document.getElementById 或 querySelector 获取 iframe 元素后,可用 .contentWindow 或 .contentDocument 访问内部对象:
-
iframe.contentWindow:指向 iframe 内的window对象,可调用其方法(如alert)、监听事件、访问location等 -
iframe.contentDocument:等价于iframe.contentWindow.document,用于读写内部 DOM(仅同源) - 注意:iframe 必须已加载完成(监听
load事件),否则 contentDocument 可能为 null
同源 iframe 的 DOM 操作示例
假设 iframe 与父页同域(如都在 https://example.com):
const iframe = document.getElementById('myIframe');
iframe.addEventListener('load', () => {
const innerDoc = iframe.contentDocument;
const h1 = innerDoc.querySelector('h1');
h1.textContent = '标题已被父页修改';
});
登录后复制
也可执行脚本:iframe.contentWindow.eval('console.log("hello from parent")')(不推荐,有安全风险)
立即学习“Java免费学习笔记(深入)”;
跨域 iframe 通信:postMessage
父页向子页发消息:
标签: javascript java js ai win 跨域
还木有评论哦,快来抢沙发吧~