vue中iframe使用详解,结合postMessage实现跨域通信

使用场景

需求:在一个H5项目的页面中以url的方式嵌入另一个项目的页面。(不得不使用iframe)

而为了兼容移动端api(封装的一个移动端api,iframe内嵌页面不生效),需要实现父子页面的通信 (使用postMessage)。

iframe使用

基本使用

直接在页面嵌套iframe标签指定src即可使用iframe。

<iframe src="xxx.html">iframe>

常用属性

  1. frameborder:是否显示边框,1(yes),0(no)
  2. height:框架作为一个普通元素的高度。
  3. width:框架作为一个普通元素的宽度。
  4. name:框架的名称,window.frames[name]时专用的属性。
  5. scrolling:框架的是否滚动。yes,no,auto。
  6. src:内框架的地址,可以使页面地址,也可以是图片的地址。
  7. sandbox:对iframe进行一些列限制,IE10+支持

更多属性访问: https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/iframe

iframe高度自适应

let ifr = document.getElementById('ifr')
const deviceHeight = document.documentElement.clientHeight;
ifr.style.height = (Number(deviceHeight)) + 'px'; 

vue中需要在mounted()中进行高度初始化

获取iframe的内容

  1. 通过两个主要的API:contentWindowcontentDocument

    • iframe.contentWindow,获取iframe的window对象
    • iframe.contentDocument,获取iframe的document对象
    var iframe = document.getElementById("iframe1");
    var iwindow = iframe.contentWindow;
    var idoc = iwindow.document;
    
    console.log("window",iwindow);	//获取iframe的window对象
    console.log("document",idoc);	//获取iframe的document
    console.log("html",idoc.documentElement);	//获取iframe的html
    console.log("head",idoc.head);	//获取head
    console.log("body",idoc.body);	//获取body
    
  2. 通过Name属性,通过window提供的frames获取