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

问题描述

  • 主要是用变量对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)

你可能感兴趣的:(Angular,笔记,Web,javascript,前端,angular.js,typescript,前端)