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>

相关推荐
帅那个帅6 分钟前
PHP里面的抽象类和接口类
开发语言·php
程序员码歌6 小时前
短思考第261天,浪费时间的十个低效行为,看看你中了几个?
前端·ai编程
咖啡の猫6 小时前
Python字典推导式
开发语言·python
Swift社区6 小时前
React Navigation 生命周期完整心智模型
前端·react.js·前端框架
若梦plus6 小时前
从微信公众号&小程序的SDK剖析JSBridge
前端
leiming66 小时前
C++ vector容器
开发语言·c++·算法
SystickInt7 小时前
C语言 strcpy和memcpy 异同/区别
c语言·开发语言
用泥种荷花7 小时前
Python环境安装
前端
CS Beginner7 小时前
【C语言】windows下编译mingw版本的glew库
c语言·开发语言·windows
Light607 小时前
性能提升 60%:前端性能优化终极指南
前端·性能优化·图片压缩·渲染优化·按需拆包·边缘缓存·ai 自动化