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>

相关推荐
杜子不疼.几秒前
Python多模态AI开发指南:让AI同时理解文字、图片和语音
开发语言·人工智能·python
IT_陈寒1 分钟前
SpringBoot自动配置的坑把我埋了半小时
前端·人工智能·后端
专注VB编程开发20年3 分钟前
VBA/VB6连接、读取Mdb access数据库最快的方法
前端·ui·ado·vb6
逻辑驱动的ken4 分钟前
Java高频面试考点04
java·开发语言·算法·哈希算法·散列表
小饕4 分钟前
RAG学习之 - 检索质量评估指标详解:从概念到代码实战
开发语言·人工智能·python·学习
John.Lewis6 分钟前
C++加餐课-继承和多态:扩展学习
开发语言·c++·笔记
XMYX-08 分钟前
12 - Go Slice:底层原理、扩容机制与常见坑位
开发语言·golang
codeejun9 分钟前
每日一Go-50、Go微服务--配置中心
开发语言·微服务·golang
泽020211 分钟前
LLMChat ----- 通过C++语言调用大语言模型所实现的聊天系统
开发语言·c++·语言模型
蒸汽求职13 分钟前
告别静态文档:利用 Notion 搭建“交互式”简历的降维展示策略
开发语言·缓存·面试·职场和发展·金融·notion