什么是Angular的SafeUrl [英] What is Angular's SafeUrl

查看:535
本文介绍了什么是Angular的SafeUrl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档仅表示:

标记界面,可以安全地用作链接到文档的URL.

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

我什么时候应该使用SafeUrl?

推荐答案

您可以将SafeUrlDomSanitizer一起使用,以告知Dom应用程序信任URL.

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

Angular默认将所有值视为不可信.当一个值是 通过属性,属性,样式从模板插入DOM, 类绑定或插值,Angular清除并转义 不可信的价值观.

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>

在您的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上下文中使用的不安全值

unsafe value used in a resource URL context

为避免这种情况,请将SafeUrlDomSanitizer结合使用,以告诉应用程序所使用的动态URL受信任:

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

请参见工作演示.

这篇关于什么是Angular的SafeUrl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆