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

本文详细介绍了在Vue项目中如何使用iframe,包括基本使用、属性设置、高度自适应,以及如何利用postMessage实现跨域通信。重点讲述了在同域和跨域环境下,父子页面内容的获取,并提供了在Vue中使用postMessage进行通信的实例代码。
摘要由CSDN通过智能技术生成

使用场景

需求:在一个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
  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值