iframe 内嵌跨域页面如何做到高度自适应

场景描述:

parent.html 页面中通过iframe内嵌children.html页面,且children.html 页面高度是动态变化的,此时需要parent.html中的iframe的高度自适应children.hml 的高度,避免出现滚动条., 解决方法分为以下两步

1,parent.html 中通过iframe 内嵌children.html 页面,监听message 消息,接收返回参数设置iframe 的高度

// my-src 对应的是childrem.html 页面的地址

<iframe

ref="iframeRef"

license="xxxx"

width="100%"

class="iframe-msg-content"

src="my-src"

frameborder="0"

></iframe>

<script setup>

import {onMounted, onUnmounted} from 'vue';

const handleMessage = (event: MessageEvent) => {

if (Object.prototype.toString.call(event.data) === '[object String]') {

// 过滤来自webPack发送的possMessage 消息

const message = JSON.parse(event.data);

if (message?.type === 'HEIGHT') {

// 设置iframe 的高度

iframeRef.value.style.height = message.data.height + 'px';

}

}

};

onMounted(()=>{

window.addEventListener('message', handleMessage, false);

});

onUnmounted(() => {

window.removeEventListener('message', handleMessage, false);

});

</script>

// 先给一个默认的宽高

.iframe-msg-content{

width: 100%;

height: 400px

}

2,在children.html 页面中监听自身最外层标签的尺寸变化,并将变化后的尺寸发送给parent.html页面

// child.html最外层元素 .page-container

<div class="page-container" ref="pageContainer"></div>

<script setup lang="ts">

import {ref,reactive, onMounted, onUnmounted} from "vue";

const pageContainer = ref();

const state = reactive({

resizeObserve: null as ResizeObserver|null,

})

onMounted(()=>{

nextTick(() => {

if (!state.resizeObserve) {

state.resizeObserve = new ResizeObserver((entires) => {

for (const entry of entires) {

if (entry.target === pageContainer.value) {

const message = {

type: 'HEIGHT',

data: {

height: pageContainer.value?.offsetHeight,

},

};

// 此时监听统计图dom尺寸的改变,重载统计图

window.parent.postMessage(JSON.stringify(message), 'ip+端口');

}

}

});

}

state.resizeObserve.observe(pageContainer.value as any);

});

})

</script>

相关推荐
LPieces1 小时前
【LPieces-UI】01-从零开始搭建 Vue3 组件库
前端
学习使我快乐011 小时前
AI时代下,前端如何破局
前端·人工智能
凯瑟琳.奥古斯特1 小时前
SpringBoot快速入门指南
java·开发语言·spring boot·后端·spring
江屿风1 小时前
【c++笔记】类和对象流食般投喂(上)
开发语言·c++·笔记
xyq20241 小时前
Lua 模块与包
开发语言
yingyima2 小时前
Unix 时间戳转换实战:一次差点毁掉项目的低级错误
前端
小短腿的代码世界2 小时前
打印不止是QPrinter:深入Qt Print Support框架的内核设计与跨平台输出管道
开发语言·qt
性野喜悲2 小时前
python将excel中的链接转成图片并替换链接展示在excel中【将pdf的第一页插入excel并将对应信息获取到插入签名等位置】
开发语言·python·excel
诙_2 小时前
C++代码实践应用
开发语言·c++
谙弆悕博士2 小时前
【附C语言源码】从零实现命令行贪吃蛇游戏
c语言·开发语言·学习·游戏·游戏程序·小游戏·贪吃蛇