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:某些交互还需要父页面和子页面共同实现,比如从高度大的页面跳转到高度小的页面时,需要返回顶部。

相关推荐
晨米酱31 分钟前
四、Prettier 编辑器集成指南
前端·代码规范
文心快码BaiduComate36 分钟前
Comate 4.0新年全面焕新!底层重构、七大升级、复杂任务驾驭力跃升
前端·程序员·架构
怪可爱的地球人1 小时前
uni-app:5 步接入 vite-plugin-uni-pages,用 <route> 自动生成 pages.json
前端
前端Hardy1 小时前
告别 !important:现代 CSS 层叠控制指南,90% 的样式冲突其实不用它也能解
前端·vue.js·面试
前端Hardy1 小时前
Vue 3 性能优化的 5 个隐藏技巧,第 4 个连老手都未必知道
前端·vue.js·面试
炫饭第一名1 小时前
速通Canvas指北🦮——路径与形状篇
前端·javascript·程序员
DeathGhost1 小时前
CSS container容器查询
前端·css
JarvanMo1 小时前
Flutter:展示大段格式化文本的挑战
前端
兆子龙1 小时前
Node.js ESM Loader Hooks 介绍:用 module.register 做转译、Import Map 与自定义解析
前端
四眼肥鱼1 小时前
flutter 利用flutter_libserialport 实现SQ800 串口通信
前端·flutter