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

Angular 15多Iframe自适应高度问题:如何让各iframe尺寸独立

问题原因

当前所有绑定了appAdjustIframeHeight指令的iframe,都会监听全局的window:message事件。当任意一个iframe发送高度调整消息时,所有指令实例都会触发回调并修改自身绑定的iframe高度,最终导致所有iframe都应用最后一条消息中的高度值。

解决方案

通过message事件的event.source属性判断消息来源,仅处理当前指令绑定的iframe发送的消息(每个iframe的contentWindow是唯一的,与event.source一一对应)。

修改后的指令代码如下:

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appAdjustIframeHeight]'
})
export class AdjustIframeHeightDirective {
  constructor(private el: ElementRef) {
  }

  @HostListener('window:message', ['$event'])
  onMessage(event: MessageEvent): void {
    const iframe = this.el.nativeElement as HTMLIFrameElement;
    
    // 仅处理当前iframe发送的消息
    if (event.source !== iframe.contentWindow) {
      return;
    }

    try {
      const messageData = JSON.parse(event.data);
      const details = messageData.details;
      
      if (details && details.height) {
        iframe.style.height = `${details.height}px`;
      }
    } catch (error) {
      // 忽略非目标格式的全局消息,避免解析报错
      return;
    }
  }
}
补充说明
  1. 来源匹配逻辑:event.source是发送消息的窗口对象,与当前iframe的contentWindow完全对应,通过对比可确保每个指令只处理自身绑定iframe的高度消息。
  2. 异常处理:增加try-catch块,避免页面中其他非JSON格式的全局消息导致代码报错。
  3. 无需额外标识:不需要依赖data-iframe-id这类自定义属性,通过窗口对象匹配的方式更可靠。

内容的提问来源于stack exchange,提问作者Felipe Zardo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 15:02:21