使用场景
需求:在一个H5项目的页面中以url的方式嵌入另一个项目的页面。(不得不使用iframe)
而为了兼容移动端api(封装的一个移动端api,iframe内嵌页面不生效),需要实现父子页面的通信 (使用postMessage)。
iframe使用
基本使用
直接在页面嵌套iframe标签指定src即可使用iframe。
<iframe src="xxx.html"></iframe>
常用属性
- frameborder:是否显示边框,1(yes),0(no)
- height:框架作为一个普通元素的高度。
- width:框架作为一个普通元素的宽度。
- name:框架的名称,window.frames[name]时专用的属性。
- scrolling:框架的是否滚动。yes,no,auto。
- src:内框架的地址,可以使页面地址,也可以是图片的地址。
- 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的内容
-
通过两个主要的API:
contentWindow和contentDocument- 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

本文详细介绍了在Vue项目中如何使用iframe,包括基本使用、属性设置、高度自适应,以及如何利用postMessage实现跨域通信。重点讲述了在同域和跨域环境下,父子页面内容的获取,并提供了在Vue中使用postMessage进行通信的实例代码。
最低0.47元/天 解锁文章
3万+

被折叠的 条评论
为什么被折叠?



