4

I ran into the issue of having to sanitize an url for an iframe in Angular, yet the accepted answer provided in How to set <iframe src="..."> without causing `unsafe value` exception? does not seem to work for me.

The error thrown is ERROR Error: unsafe value used in a resource URL context

The solution I found is presented in the code below, seen in the comments here

import { Pipe, PipeTransform, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {

  constructor(private sanitizer: DomSanitizer) { }
  transform(url) {
    // commented return throws error, both with URL and with RESOURCE_URL. idk why
    // return this.sanitizer.sanitize(SecurityContext.URL, url);
    return this.sanitizer.bypassSecurityTrustResourceUrl(this.sanitizer.sanitize(SecurityContext.URL, url))
  }

}

The pipe is declared and exported in a shared module and used in an iframe tag (for now, I use a placeholder url from a youtube video)

import { NgModule } from '@angular/core';
import { SafePipe } from './pipes/safe.pipe';
@NgModule({

  declarations: [SafePipe],
  exports: [SafePipe],
})
export class SharedModule { };

html:

<iframe width="680" height="430" [src]="courseIframeUrl | safe" frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>

My question is, is this correct? The accepted answer for the first link says that bypassSecurityTrustResourceUrl is unsafe, yet the documentation calls for the method to be used for an iframe or for a script. How would a correct solution look like, if not?

Bogdan Marcu
  • 105
  • 5
  • 1
    Yes, this is fine assuming you always trust the `courseIframeUrl` value. Where it would become unsafe would be if you were allowing users to define what the value of `courseIframeUrl` is. – abney317 Aug 20 '20 at 13:37

0 Answers0