【问题标题】:What is Angular's SafeUrl什么是 Angular 的 SafeUrl
【发布时间】:2017-09-20 19:21:43
【问题描述】:

documentation 只说:

值的标记接口,可安全用作链接到文档的 URL。

什么时候应该使用SafeUrl

【问题讨论】:

    标签: angular


    【解决方案1】:

    您使用 SafeUrlDomSanitizer 告诉 Dom 您的应用信任某个 URL。

    默认情况下,Angular 将所有值都视为不受信任。当一个值为 通过属性、属性、样式从模板插入到 DOM 中, 类绑定或插值,Angular 清理和转义 不受信任的值。

    例如,执行以下操作会导致错误:

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

    在你的 ts 中:

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

    资源 URL 上下文中使用的不安全值

    为避免这种情况,您可以使用 SafeUrlDomSanitizer 告诉您应用您使用的动态 URL 是可信的:

    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);
    }
    

    看到这个working demo

    【讨论】:

    • 是否可以在帖子中使用 bypassSecurityTrustUrl?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2017-12-08
    • 2023-01-06
    • 1970-01-01
    • 2020-05-25
    • 2016-01-17
    • 2019-07-07
    相关资源
    最近更新 更多