MutationObserver 实现 iframe 自适应高度

话不多说,直接上代码。

父页面 parent.tsx

tsx 复制代码
import { useRef, useEffect } from 'react'
import authResizeIframeHeight from './authResizeIframeHeight.ts'

const Parent = () => {
  const iframeRef = useRef()

  useEffect(() => {
    authResizeIframeHeight({ iframe: iframeRef.current })
  }, [])

  return (
    <div>
      <iframe
        src='child.tsx'
        ref={iframeRef}
        width='100%'
        height='100%'
        frameBorder={0}
      />
    </div>
  )
}

export default Parent

其中 authResizeIframeHeight.ts 代码如下:

ts 复制代码
/**
 * 自适应 iframe 高度
 * @param iframe 元素
 * @returns
 */
export authResizeIframeHeight = ({ iframe }) => {
  const MIN_HEIGHT = 800
  const MAX_HEIGHT = 3000

  const handleMessage = (event) => {
    const { source, origin, data } = event
    if (!data || typeof data !== 'object' || !origin || !source) {
      return
    }

    const { type, height } = data
    const originValid = `${origin}/` === 'http://dev.jd.com'
    const sourceValid = source === iframe?.contentWindow
    const typeValid = type === 'resize-height'
    const heightValid = typeof height === 'number'
    if (originValid && sourceValid && typeValid && heightValid) {
      let finalHeight = height
      if (height < MIN_HEIGHT) {
        finalHeight = MIN_HEIGHT
      } else if (height > MAX_HEIGHT) {
        finalHeight = MAX_HEIGHT
      }
      iframe.style.height = `${finalHeight}px`
    }
  }

  window.addEventListener('message', handleMessage)

  return () => {
    window.removeEventListener('message', handleMessage) // 防止内存泄漏
  }
}

子页面 child.tsx

tsx 复制代码
/**
 * 自适应 iframe 高度
 * @returns
 */
const postMessageResize = () => {
	const targetOright = 'http://dev.jd.com';
	let lastHeight = 0;
	const mo = new MutationObserver(() => {
		const currentHeight = document.body.scrollHeight;
		if (currentHeight === lastHeight) {
			return;
		}
		lastHeight = currentHeight;
		parent.postMessage(
			{
				type: 'resize-height',
				height: currentHeight
			},
			targetOright
		);
	});
	// 开始监控 body 元素的修改:
	mo.observe(document.body, {
		attributes: false,
		childList: true,
		subtree: true
	});
};

postMessageResize();

再看看 mutationObserver 的兼容性。

IE11 都支持。

PS:某些交互还需要父页面和子页面共同实现,比如从高度大的页面跳转到高度小的页面时,需要返回顶部。

相关推荐
水银嘻嘻2 小时前
12 web 自动化之基于关键字+数据驱动-反射自动化框架搭建
运维·前端·自动化
小嘟嚷ovo3 小时前
h5,原生html,echarts关系网实现
前端·html·echarts
十一吖i3 小时前
Vue3项目使用ElDrawer后select方法不生效
前端
只可远观3 小时前
Flutter目录结构介绍、入口、Widget、Center组件、Text组件、MaterialApp组件、Scaffold组件
前端·flutter
周胡杰3 小时前
组件导航 (HMRouter)+flutter项目搭建-混合开发+分栏效果
前端·flutter·华为·harmonyos·鸿蒙·鸿蒙系统
敲代码的小吉米4 小时前
前端上传el-upload、原生input本地文件pdf格式(纯前端预览本地文件不走后端接口)
前端·javascript·pdf·状态模式
是千千千熠啊4 小时前
vue使用Fabric和pdfjs完成合同签章及批注
前端·vue.js
九月TTS4 小时前
TTS-Web-Vue系列:组件逻辑分离与模块化重构
前端·vue.js·重构
我是大头鸟5 小时前
SpringMVC 内容协商处理
前端
Humbunklung5 小时前
Visual Studio 2022 中添加“高级保存选项”及解决编码问题
前端·c++·webview·visual studio