angular直接使用iframe时动态绑定src会报错。
angular在这方面做了关于防止xss攻击的安全机制,这种做法是不符合要求的。(官方文档:https://angular.cn/guide/security)
解决方法:
新建管道safe-pipe
safe-pipe.pipe.ts
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);
}
}
|
safe-pipe.module.ts
import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { SafePipe } from "./safe-pipe.pipe";
@NgModule({
imports: [CommonModule],
declarations: [SafePipe],
exports: [SafePipe]
})
export class SafePipeModule {}
|
将SafePipeModule暴露给外部使用,在module中
exports: [SafePipeModule]
在使用iframe的时候
<iframe [src]="cSrc | safe" width="640" height="360" allowfullscreen allow="autoplay"></iframe>
|