Angular 15忽略iframe元素问题咨询:是Bug还是操作遗漏?
Angular 15中iframe消失的原因及解决方法
这不是Angular的Bug,是因为忽略了Angular的安全防护机制导致的。
Angular为了防范XSS攻击,会自动拦截并移除被判定为“不安全”的内容。当直接给iframe的src赋值普通字符串时,Angular会认为该资源地址存在安全风险,直接将iframe元素从DOM中移除。
解决方法很简单,通过DomSanitizer工具处理资源地址即可:
- 在组件中注入
DomSanitizer并处理URL:
import { Component } from '@angular/core'; import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; @Component({ selector: 'app-root', templateUrl: './app.component.html', }) export class AppComponent { constructor(private sanitizer: DomSanitizer) {} // 处理目标URL,替换成你实际要嵌入的地址 get trustedIframeUrl(): SafeResourceUrl { return this.sanitizer.bypassSecurityTrustResourceUrl('https://你要嵌入的资源地址'); } }
- 在模板中绑定处理后的安全URL:
<iframe [src]="trustedIframeUrl" width="600" height="400"></iframe>
你提到的StackBlitz示例无法运行,大概率也是因为没有做上述安全处理,直接使用了未经过滤的URL,被Angular的安全机制拦截了。
内容的提问来源于stack exchange,提问作者Ya.
相关产品推荐
相关产品推荐

