Angular 异常 NG0904: unsafe value used in a resource URL context

在Angular应用中,直接给iframe的src赋值可能会引发安全问题。为了解决这个问题,文章介绍了使用DomSanitizer来bypasssecuritytrustforaresourceURL。通过创建一个SafePipe,我们可以将不安全的URL转化为可信任的资源,然后在模板中通过管道操作符安全地设置iframe的src属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述
  • 主要是用变量对iframe页面的参数进行赋值时报错,直接使用字符串不会报错、
故障原因

-因为在iframe中执行angular不信任的操作,需要使用angular提供的DomSanitizer

解决办法
  • 使用Angular提供的DomSanitizer
  url: any;
	
  constructor(
    private sanitizer: DomSanitizer
  ) {}

  ngOnInit() {
    setTimeout(() => {
      this.url = this.sanitizer.bypassSecurityTrustResourceUrl(
        `http://www.baidu.com`
      );
    }, 1000);
  }
  • 创建一个Pipe
import { Pipe, PipeTransform} from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) { }
  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
}

声明Pipe

@NgModule({
  imports: [ ... ],
  declarations: [ ..., SafePipe ],
  bootstrap: [ App ]
})

使用pipe

 <iframe [src]="your_url_here | safe" id="inneriframe" scrolling="no"  ></iframe>
参考链接

1.Unsafe value used in a resource URL context (iframe)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值