Angular 2 – EXCEPTION: Error: unsafe value used in a resource URL context

Issue

I am getting the following error:

Angular 2 – EXCEPTION: Error: unsafe value used in a resource URL context

Could it be related to not having the media item straight away on startup? Or is it related to the URL not being safe? I am trying to sanitize it.

export class HomeComponent {

  sanitizer: DomSanitizationService;
  errorMessage: string;
  activeMedia: MediaItem = new MediaItem(0, '', '', '', '', '', '');

  constructor(
    private mediaStorage: MediaStorageService, 
    private harvesterService: HarvesterService, 
    sanitizer: DomSanitizationService) {

    this.sanitizer = sanitizer;
    // Initial call - 
    harvesterService.getMediaItems(10, 'type', 'category');
    let subscription = harvesterService.initialMediaHarvestedEvent.subscribe(() => {
      this.activeMedia = mediaStorage.mediaList[0];
      let newURL = this.activeMedia.URL + '?rel=0&autoplay=1';
      newURL = newURL.replace('watch?v=', 'v/');
      this.activeMedia.URL = newURL; //sanitizer.bypassSecurityTrustUrl(newURL);
      console.log(newURL);
    });
  }

  cleanURL(oldURL: string): SafeResourceUrl {
    return this.sanitizer.bypassSecurityTrustUrl(oldURL);
  }
}

The template code is:

<div class="row" >
    <iframe 
      id="video"  
      class="video" 
      src="{{ cleanURL(activeMedia.URL) }}" 
      frameborder="0" 
      allowfullscreen>
    </iframe>
</div>

Solution

UPDATED: After changing the

 src="{{cleanURL(activeMedia.URL)}}"

to:

 [src]="cleanURL(activeMedia.URL)"

I’m getting: ORIGINAL EXCEPTION: Error: Required a safe ResourceURL, got a URL

which is solved with changing the code within the cleanURL method to:

 return this.sanitizer.bypassSecurityTrustResourceUrl(oldURL);

Instead of:

 return this.sanitizer.bypassSecurityTrustUrl(oldURL);

Answered By – Pete

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.