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>

相关推荐
普通网友21 分钟前
基于C++的操作系统开发
开发语言·c++·算法
狂团商城小师妹25 分钟前
JAVA外卖霸王餐CPS优惠CPS平台自主发布小程序+公众号霸王餐源码
java·开发语言·小程序
2501_941111341 小时前
C++中的策略模式高级应用
开发语言·c++·算法
心软小念2 小时前
用Python requests库玩转接口自动化测试!测试工程师的实战秘籍
java·开发语言·python
sanggou3 小时前
【Python爬虫】手把手教你从零开始写爬虫,小白也能轻松学会!(附完整源码)
开发语言·爬虫·python
普通网友3 小时前
C++与Qt图形开发
开发语言·c++·算法
!win !3 小时前
前端跨标签页通信方案(下)
前端·javascript
f***45323 小时前
基于SpringBoot和PostGIS的各省与地级市空间距离分析
android·前端·后端
编码追梦人4 小时前
从 “手忙脚乱“ 到 “行云流水“:华为云 DevUI 与 MateChat 如何让前端开发飞起来
前端·华为云
yue0084 小时前
C# 更改窗体样式
开发语言·c#