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>

相关推荐
前端那点事2 分钟前
Vuex刷新数据丢失?4种持久化方案全覆盖,从零到项目落地(实战完整版)
前端·vue.js
Cerrda2 分钟前
性能提升 satisfying!一个 Vue3 指令干掉页面上 200 个无用 Tooltip 实例
前端·设计
漫游的渔夫2 分钟前
前端开发者做 AI Agent:别只渲染答案,用 7 个状态接住确认、错误和 trace
前端·人工智能·typescript
clove2 分钟前
从 LLM 到 Agent:一篇文章课带你彻底搞懂 AI 智能体的核心逻辑
前端
顾温3 分钟前
协程结束——实测
开发语言·unity·c#
前端那点事4 分钟前
彻底吃透JS定时器!setTimeout/setInterval区别、坑点与最优优化方案(Vue实战)
前端·vue.js
费曼学习法7 分钟前
Vue 3 编译优化揭秘:静态提升与 PatchFlags 的极致性能
javascript·vue.js
ZC跨境爬虫9 分钟前
跟着 MDN 学 HTML day_27:(深入理解 HTML 属性反射机制)
前端·javascript·ui·html·音视频·媒体
ayqy贾杰14 分钟前
过去三年我做对了一件事
前端·面试·ai编程
小矮马20 分钟前
qiankun 微前端集成子项目
javascript