当前位置:主页 > 查看内容

iframe 使用

发布时间:2021-06-12 00:00| 位朋友查看

简介:iframe 与父页面的主动交互 父页面与 iframe 交互 /** * 父页面获取 iframe window 对象 */const iframeWin = document.getElementById("iframe").contentWindow;const iframeWin = document.getElementsByTagName('iframe')[0].contentWindow;/** * 父页面……

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。

问题
在 D 中跳转页面

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

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

链接或form
D 页面中有form

/**
 * 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();

本文转自网络,版权归原作者所有,原文链接:https://segmentfault.com/a/1190000040164243
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!
上一篇:实时计算 Flink 版总体介绍 下一篇:没有了

推荐图文


随机推荐