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; } } }
补充说明
- 来源匹配逻辑:
event.source是发送消息的窗口对象,与当前iframe的contentWindow完全对应,通过对比可确保每个指令只处理自身绑定iframe的高度消息。 - 异常处理:增加
try-catch块,避免页面中其他非JSON格式的全局消息导致代码报错。 - 无需额外标识:不需要依赖
data-iframe-id这类自定义属性,通过窗口对象匹配的方式更可靠。
内容的提问来源于stack exchange,提问作者Felipe Zardo
相关产品推荐
相关产品推荐

