You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态设置iframe高度失效:所有iframe均被赋值为最后一个的高度

问题根因

  • 循环内重复给window绑定message事件监听器,且由于闭包特性,所有监听器内部引用的ifrm变量最终都会指向循环结束时的最后一个iframe实例,无论哪个iframe返回高度,都会作用到最后一个iframe上。
  • 没有对返回的消息来源做区分,无法匹配高度对应的目标iframe。

修复方案

全局只绑定一次message监听器,收到消息后通过event.source匹配对应的iframe再设置高度,修正后的完整代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
</head>
<body>
    <iframe
    src="https://embed.kooapp.com/embedKoo?kooId=91f35ac5-dd15-4271-bb36-b9793131399a"
    name="kooFrame"
    id="1"
    ></iframe>
    <iframe
    src="https://embed.kooapp.com/embedKoo?kooId=803857a6-2a9d-4c70-9731-69213e80fbf0"
    name="kooFrame"
    id="2"
    ></iframe>
    
    <script>
      const iframes = document.getElementsByName('kooFrame');
      // 全局只绑定一次message监听器
      window.addEventListener('message', (event) => {
        if (!event.data.hasOwnProperty('FrameHeight')) return
        const height = event.data.FrameHeight
        // 匹配发送消息的iframe
        for (let i = 0; i < iframes.length; i++) {
          if (iframes[i].contentWindow === event.source) {
            iframes[i].style.height = `${height}px`
            break
          }
        }
      })

      window.onload = () => {
        for (let i = 0; i < iframes.length; i++) {
          const ifrm = iframes[i];
          ifrm.scrolling = 'no';
          ifrm.frameBorder = 0;
          ifrm.allowFullScreen = true;
          ifrm.allowTransparency = true;
          ifrm.style.width = '100%';
          ifrm.contentWindow.postMessage('FrameHeight', '*');
        }
      }
    </script>
</body>
</html>

内容的提问来源于stack exchange,提问作者Akash Chavda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:51:02