How can I display SafeUrl or SafeResourceUrl?

I am loading a trusted url in an iframe which works fine. I also want to display this url as a string on the page. I tried <div>{{url}}</div>

, but it displays:

SafeValue must use [property] = binding: /my/resource/path.html (see http://g.co/ng/security#xss )

I also tried to use <div [ngModel]="url"></div>

but got

Error: No accessor for a form control with an undefined name attribute

How do I display it?

+3


source to share


3 answers


You can do it differently:



<iframe #foo [src]="contentUrl"></iframe>
<p>{{ foo.src }}</p>

      

+1


source


  • The error says use [property] binding - this means [innerHTML] for html
  • You want to render this value as html (not url or resource) - use bypassSecurityTrustHtml

     @Component({
      selector: 'my-app',
      template: `
        <div [innerHTML]="url"><div>
      `
     })
    export class App {
    
      dangerousVideoUrl = "href='&#x3000;javascript:alert(1)'";
    
      constructor(private sanitizer: DomSanitizer) {
        this.url =
        this.sanitizer.bypassSecurityTrustHtml(this.dangerousVideoUrl);
     }
    }
    
          



+2


source


Try using it @Pipe

to use this throughout your application and DomSanitizer

to sanitize the url and bypass the XSS security.

@Pipe({
    name: 'sanitizeUrl',
    pure: false
})
export class AsString implements PipeTransform {
    constructor(private domSanitizer: DomSanitizer) {
    }

    transform(value: string, args?: any): any {            
        return this.domSanitizer.bypassSecurityTrustResourceUrl(value);
    }
}

      

And in your template:

<div>{{url | sanitizeUrl}}</div>

      

0


source







All Articles