0

I am trying to load the iFrame on Angular2 . However the address is loaded dynamically .

The live code is : https://angular-fgzjog.stackblitz.io

Inside app.coponent.ts

<!-- this works -->
    <p>
     iframe address  : {{iFrameSrc}} 
    </p>

<!--- this does not work -->
    <div class="embed-responsive embed-responsive-16by9">
                    <iframe class="embed-responsive-item" [src]="iFrameSrc"></iframe> 
                  </div>
RajDev
  • 160
  • 3
  • 8

1 Answers1

2

Angular is sanitizing whatever you try to put into the iframe src to prevent unsafe content. Therefore you must sanitize your url to tell Angular that you intentionally add this url and that it is safe!

https://angular.io/api/platform-browser/DomSanitizer

So either add this logic to your component and call:

constructor(
 private domSanitizer: DomSanitizer, 
 // ...
) // ...

this.safeiFrameSrc = this.domSanitizer.bypassSecurityTrustUrl(this.iFrameSrc)


<!-- template binding: -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" [src]="safeiFrameSrc"></iframe> 
</div>

Or you could also create a pipe:

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  constructor(protected sanitizer: DomSanitizer) {}

  transform(value: string, type: string = 'url'): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html':
        return this.sanitizer.bypassSecurityTrustHtml(value);
      case 'style':
        return this.sanitizer.bypassSecurityTrustStyle(value);
      case 'script':
        return this.sanitizer.bypassSecurityTrustScript(value);
      case 'url':
        return this.sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl':
        return this.sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        throw new Error(`Unable to bypass security for invalid type: ${type}`);
    }
  }
}

<!-- usage: -->

<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" [src]="iFrameSrc | safe"></iframe> 
</div>    

This should resolve the issue!

OClyde
  • 1,036
  • 6
  • 11
  • Nice, glad to hear! Just seeing the error when outputting the url directly, this is just intended by Angular to tell you that you are only supposed to use this in a binding as it states to not expose safe urls directly somewhere! However, that's just a side note and you don't want to do this in production anyways I assume! :) – OClyde Mar 21 '18 at 11:10