iframe 使用

iframe 与父页面的主动交互

父页面与 iframe 交互

/**
 * 父页面获取 iframe window 对象
 */
const iframeWin = document.getElementById("iframe").contentWindow;
const iframeWin = document.getElementsByTagName('iframe')[0].contentWindow;
/**
 * 父页面获取 iframe document 对象
 */
const iframeDoc = iframeWin.document;
/**
 * 父页面获取 iframe body 对象
 */
const iframeBody = iframeDoc.body;
/**
 * 父页面调用 iframe 方法
 */
iframeWin.method(); // method 是 iframe 的一个方法名

iframe 与父页面交互

/**
 * iframe 获取父页面 window 对象
 */
const parentWin = window.parent;
/**
 * iframe 获取父页面 document 对象
 */
const parentDoc = window.parent.document;
/**
 * iframe 获取父页面 window 对象
 */
const parentBody = window.parent.body;
/**
 * iframe 调用父页面的方法
 */
window.parent.method(); // method 是父页面的方法

iframe 与父页面传递数据

window.postMessage 是容许两个(跨域)窗口或 iframes 发送数据信息。像是跨域的AJAX,但不是浏览器跟服务器之间交互,而是在两个客户端之间通讯。更多信息查看 window.postMessage跨域

发送消息:浏览器

/**
 * iframe 页面发送消息
 */
const message = 'Hello!'; // 发送到其余 window的数据
const domain = '*'; // 指定哪些窗口能接收到消息事件,‘*’表示无限制
window.postMessage(message, domain);

接收消息:服务器

/**
 * data: 发送方窗口发送的数据
 * origin: 发送方窗口的 origin 
 * source: 发送消息的窗口对象的引用
 */
window.addEventListener('message', (event) => {
  const { data, origin, source } = event
  console.log(event)
}, false);

嵌套 ifream 跳转

背景
A, B, C, D 是四个页面,B 是 A 的 iframe,C 是 B 的 iframe,D 是 C 的 iframe。dom

问题
在 D 中跳转页面post

跳转
使用 window.open() 是相似的。code

/**
 * 在本页面跳转(D 页面跳转)
 */
window.location.href = '';
/**
 * 在上一层页面跳转(C 页面跳转)
 */
window.parent.location.href = '';
/**
 * 在上上一层页面跳转(B 页面跳转)
 */
window.parent.parent.location.href = '';
/**
 * 在最外层页面跳转(A 页面跳转)
 */
window.top.location.href = '';

连接或form
D 页面中有formorm

/**
 * form 提交后,在 D 页面跳转
 */
<form></form>
/**
 * form 提交后,弹出新页面
 */
<form target="_blank"></form>
/**
 * form提交后,在 C 页面跳转
 */
<form target="_parent"></form>
/**
 * form提交后,在 A 页面跳转
 */
<form target="_top"></form>

刷新对象

/**
 * C 页面刷新
 */
window.parent.location.reload();
/**
 * A 页面刷新
 */
window.top.location.reload();
相关文章
相关标签/搜索