关于iframe

关于iframe的一些事情

一 iframe简介

iframe是一个行内标签,在一个页面中使用iframe标签,通过src可以链接到其他页面。当前页面也可通过设置 X-Frame-Options:'sameorigin',只允许同源访问。

二 iframe通信

1.同源通信

通过在父页面中中获取iframe页面的window,通过window去调用子页面的全局函数实现 父向子传值;

  /*父页面*/
  <iframe id='child' scr='*'></iframe>
  <script>
    const child = document.querySelector('#child');
    child.contentWindow.on(x);
  </script>
  /*子页面*/
  <script>
    function on(message){
      console.log(message);
    };
  </script>

2.非同源通信

父页面通过iframeDom.postMessage 来发送数据, 子页面通过window.onmessage 来监听发送过来的数据

  /*父页面*/
  <iframe id='child' scr='*'></iframe>
  <script>
    const child = document.querySelector('#child');
    child.postMessage(x,y); // x 表示传递数据,y表示url,可以设置为'*'
  </script>
  /*子页面*/
  <script>
    const fn = (e)=>{
      console.log(e.data);
    };
    window.addEventLisener= ('message',fn)
  </script>

二 关于页面的跳转

a标签的target属性

_self: 在当前tab中进行跳转;// 如果iframe子页面中使用这个属性,会在iframe中进行跳转;
_blank: 新开一个tab进行跳转 // iframe子页面中,和父页面表现一致
_parent: 在iframe中生效,表示在当前iframe页面外一层的父页面中进行跳转,可以外层的一个iframe,也可以是最外层主页面
_top: 在iframe中生效,表示当前iframe最外层的主页面中进行跳转

location.href 进行跳转

location.href: 在当前页面进行跳转;// 如果在iframe的子页面中进行使用,会在当前iframe内部进行跳转页面;
window.parent.location.herf: 在iframe子页面中使用,表示在父页面中跳转
window.top.location.href: 在iframe子页面中使用,表示在顶层页面中跳转
window.open('*'); // 新开一个tab页跳转

三 利用iframe进行跨域

四 利用iframe进行前端打印

五 微前端

posted on 2022-10-01 01:23  长安城下翩翩少年  阅读(59)  评论(0编辑  收藏  举报