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

相关推荐
梦鱼16 分钟前
Vue 项目图标一把梭:Iconify 自用小记(含 TS/JS 双版本组件)
前端·javascript·vue.js
best66617 分钟前
Flex 与 Grid 的 order 参数:布局界的 "插队神器"
前端
小噔小咚什么东东18 分钟前
看到了很多次WebRTC,但是你真的需要它吗?
前端·webrtc
猫七先生19 分钟前
微信小程序一键登录可行性方案
前端·微信小程序
维他AD钙19 分钟前
前端开发 8 个非常实用小技巧:高效解决日常开发痛点
前端
光影少年24 分钟前
webpack和vite优化方案都有哪些
前端·webpack·node.js
给月亮点灯|25 分钟前
Vue基础知识-脚手架开发-初始化目录解析
前端·javascript·vue.js
kk不中嘞27 分钟前
Webpack 核心原理剖析
前端·webpack·node.js
Yvonne爱编码30 分钟前
简述ajax、node.js、webpack、git
前端·git·ajax·webpack·node.js·visual studio
周小码31 分钟前
CesiumJS详解:打造专业级Web 3D地球仪与地图的JavaScript库
前端·javascript·3d