【发布时间】:2017-09-20 19:21:43
【问题描述】:
【问题讨论】:
标签: angular
【问题讨论】:
标签: angular
您使用 SafeUrl 和 DomSanitizer 告诉 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 上下文中使用的不安全值
为避免这种情况,您可以使用 SafeUrl 和 DomSanitizer 告诉您应用您使用的动态 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。
【讨论】: