如何设置< iframe src ="...">不会导致“不安全值"异常? [英] How to set <iframe src="..."> without causing `unsafe value` exception?

查看:253
本文介绍了如何设置< iframe src ="...">不会导致“不安全值"异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个涉及设置iframe src属性的教程:

I am working on a tutorial involving the setting of an iframe src attribute:

<iframe width="100%" height="300" src="{{video.url}}"></iframe>

这将引发异常:

Error: unsafe value used in a resource URL context
at DomSanitizationServiceImpl.sanitize...

我已经尝试将绑定与[src]一起使用没有成功.

I have already tried using bindings with [src] with no success.

推荐答案

更新v8

以下答案有效,但使您的应用程序面临XSS安全风险!. 建议不要使用this.sanitizer.bypassSecurityTrustResourceUrl(url)

Below answers work but exposes your application to XSS security risks!. Instead of using this.sanitizer.bypassSecurityTrustResourceUrl(url), it is recommended to use this.sanitizer.sanitize(SecurityContext.URL, url)

更新

对于 RC.6 ^ 版本,请使用 DomSanitizer

柱塞

Plunker

一个不错的选择是为此使用纯管道:

And a good option is using pure pipe for that:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer} from '@angular/platform-browser';

@Pipe({ name: 'safe' })
export class SafePipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}
  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }
} 

请记住将新的SafePipe添加到AppModule的declarations数组中. (在文档中看到)

remember to add your new SafePipe to the declarations array of the AppModule. (as seen on documentation)

@NgModule({
   declarations : [
     ...
     SafePipe
   ],
})

html

<iframe width="100%" height="300" [src]="url | safe"></iframe>

柱塞

Plunker

如果您使用embed标签,这可能对您很有趣:

If you use embed tag this might be interesting for you:

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