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>

相关推荐
吴声子夜歌1 分钟前
ES6——Calss详解
javascript·es6·原型模式
摇滚侠2 分钟前
HTML CSS 演示小米 logo 的变化 border-radius 属性设置圆角
前端·css·html
❆VE❆3 分钟前
虚拟列表原理与实战运用场景详解
前端·javascript·css·vue.js·html·虚拟列表
weixin_408099675 分钟前
【实战教程】EasyClick 调用 OCR 文字识别 API(自动识别屏幕文字 + 完整示例代码)
前端·人工智能·后端·ocr·api·安卓·easyclick
添尹7 分钟前
Go语言基础之指针
开发语言·后端·golang
Bigger8 分钟前
第四章:我是如何扒开 Claude Code 记忆与上下文压缩机制的
前端·claude·源码阅读
2401_8274999910 分钟前
python项目实战10-网络机器人01
开发语言·python
哆啦阿梦11 分钟前
Java AI 应用工程师 - 完整技能清单
java·开发语言·人工智能
还在忙碌的吴小二12 分钟前
在 Mac 上安装并通过端口调用 Chrome DevTools MCP Server(谷歌官方 MCP 服务器)
服务器·前端·chrome·macos·chrome devtools
VT LI13 分钟前
Lua 源码执行流程全解析:词法分析、语法分析、字节码生成、虚拟机执行与垃圾回收
java·开发语言·lua