What is Angular's SafeUrl

后端 未结 1 1240
盖世英雄少女心
盖世英雄少女心 2020-12-06 03:25

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

相关标签:
1条回答
  • 2020-12-06 04:13

    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.

    0 讨论(0)
提交回复
热议问题