Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Angular's SafeUrl

Tags:

angular

The documentation only says:

Marker interface for a value that's safe to use as a URL linking to a document.

When should I use SafeUrl?

like image 784
BuZZ-dEE Avatar asked Sep 19 '17 14:09

BuZZ-dEE


1 Answers

You use SafeUrl along with DomSanitizer to tell the Dom that a URL is trusted by your app.

Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

For example, doing the following will result in an error:

<iframe [src]="iframeSrc"></iframe>

in your ts:

export class AppComponent  {
  iframeSrc: string;
  constructor(){
      let id = 's7L2PVdrb_8'; // Game of Thrones Intro Video
      this.iframeSrc = `https://www.youtube.com/embed/${id}`;
  }
}

unsafe value used in a resource URL context

To avoid this, you use SafeUrl with DomSanitizer to tell you app that the dynamic URL you are using is trusted:

import { DomSanitizer, SafeUrl } from '@angular/platform-browser';

export class AppComponent  {
    iframeSrc: SafeUrl;
    constructor(private sanitizer: DomSanitizer){
        let id = 's7L2PVdrb_8'; // Game of Thrones Intro Video
        let url = `https://www.youtube.com/embed/${id}`;
        this.iframeSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

See this working demo.

like image 146
Faisal Avatar answered Nov 04 '22 23:11

Faisal