Safe value must use [property]=binding after bypass security with DomSanitizer

前端 未结 5 1152
我寻月下人不归
我寻月下人不归 2020-12-05 13:18



        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 13:38

    I was getting this error when using an iframe so there I fixed using [src] as below:

    Import this:

    import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
    constructor(private sanitizer: DomSanitizer, ....other DI){}
    

    In ts file

    getSafeUrl() {
            return this.sanitizer.bypassSecurityTrustResourceUrl(this.url);     
    }
    

    In html file

    
    

    This method is quite cycle consuming as it'll call the function multiple time so it's better to sanitize URL inside lifeCycleHooks like ngOnInit().

    You can use pipes as well for better performance:

    import { Pipe, PipeTransform, SecurityContext } from "@angular/core"; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Pipe({ name: 'byPassSecurity' }) export class ByPassSecurityPipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) {} transform (value: string): SafeHtml { return this.sanitizer.bypassSecurityTrustHtml(value); } }

提交回复
热议问题