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 分钟前
企业微信消息回调开发指南:如何实时接收并处理企微消息?
前端·机器人·自动化·企业微信
何中应2 分钟前
CentOS7安装高版本Node.js
前端·centos·node.js
じ星不离月か2 分钟前
【记录】 跑马灯无限滚动
前端·css·跑马灯·无限滚动
周淳APP2 分钟前
【HTTP1、HTTP2、HTTP3】
前端·网络·网络协议·http
路弥行至2 分钟前
linux运行脚本出现错误信息 /bin/bash^M: bad interpreter解决方法
linux·运维·开发语言·经验分享·笔记·其他·bash
一直不明飞行4 分钟前
C++ pari使用的两个注意事项
开发语言·c++
夫唯不争,故无尤也7 分钟前
原始文档元数据metadata
java·前端·javascript·sql
wefly20178 分钟前
无需安装的 M3U8 在线播放器,快速实现 HLS 流预览与调试
java·开发语言·python·开发工具
飞Link8 分钟前
深度解析:建模动作序列(Action Sequence Modeling)的实战指南
开发语言·python·数据挖掘
CoderCodingNo8 分钟前
【GESP】C++六级/五级练习题 luogu-P1323 删数问题
开发语言·c++·算法