iframe 获取变量

父获取子

<iframe src="son.html" id="iframe" name="iframe"></iframe>
// 获取 iframe
let iframe = window.parent.document.getElementById('iframe');

// 获取 iframe window 对象
let iframeWindow =
    window.parent.document.getElementById('iframe').contentWindow;

// 获取 iframe dom
let iframeDocument =
    window.parent.document.getElementById('iframe').contentWindow.document;

// 获取变量或方法
let sonWindow = window.parent.document.getElementById('iframe').contentWindow;
// 需要加个延迟执行,否则子页面可能未执行完相关代码
setTimeout(() => {
    console.log(sonWindow.sonObj); // 子页面变量
}, 100);

window.fatherObj = '父页面变量';

子获取父

window.sonObj = '子页面变量';
let fatherIframe = window.parent;
setTimeout(() => {
    console.log(fatherIframe.fatherObj); // 父页面变量
}, 100);
Last Updated:
Contributors: zhangfei