I'm loading a trusted URL into an iframe which works fine. I also want to display that URL as a string on the page. I've 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 using <div [ngModel]="url"></div>, but got
Error: No value accessor for form control with unspecified name attribute
How can I display it?
You want to display this value as html (not url or resource) - use bypassSecurityTrustHtml
@Component({
selector: 'my-app',
template: `
<div [innerHTML]="url"><div>
`
})
export class App {
dangerousVideoUrl = "href=' javascript:alert(1)'";
constructor(private sanitizer: DomSanitizer) {
this.url =
this.sanitizer.bypassSecurityTrustHtml(this.dangerousVideoUrl);
}
}
You can do it in another way:
<iframe #foo [src]="contentUrl"></iframe>
<p>{{ foo.src }}</p>
Try with a @Pipe for using this in all your App and with DomSanitizer for sanitizing the URL and bypass 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>