Angular 2 handles sanitation using the DomSanitiser at platform-browser library, though this seems to have changed through versions this is the latest one:
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
Can be used like this in code:
constructor(private sanitizer: DomSanitizer) { this.sanitizer.bypassSecurityTrustResourceUrl("www.example.com"); }
Another way to achieve the same thing, using SecurityContext at angular/core:
import { Component, SecurityContext } from '@angular/core'; this.sanitizer.sanitize(SecurityContext.URL, "https://www.example.com");
Basically you can use sanitize adding the type of value you want to sanitise, or you can use the appropiate method for each type:
// Types SecurityContext.URL; SecurityContext.RESOURCE_URL SecurityContext.HTML SecurityContext.SCRIPT SecurityContext.STYLE // Methods this.sanitizer.bypassSecurityTrustUrl("url") this.sanitizer.bypassSecurityTrustResourceUrl("url") this.sanitizer.bypassSecurityTrustHtml("url") this.sanitizer.bypassSecurityTrustScript("url") this.sanitizer.bypassSecurityTrustStyle("url") this.sanitizer.sanitize(SecurityContext.URL, "url");
Adding URL to iframe
There’s two ways to bind the url into it:
<iframe class="video-iframe" [src]="getVideoUrl()"></iframe> <iframe class="video-iframe" src="{{getVideoUrl()}}"></iframe>
You can also use a property but I found some problems with that while the function worked better. This said, the property or function should be of type “SafeResourceUrl”:
public getVideoUrl(): SafeResourceUrl { // Notice the return type of this function is SafeResourceUrl return this.sanitizer.sanitize(SecurityContext.URL, "https://www.example.com"); }