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

查看:32
本文介绍了如何设置<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.

推荐答案

Update v8

以下答案有效,但将您的应用程序暴露于 XSS 安全风险!.建议使用 this.sanitizer.sanitize(SecurityContext.URL, 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:

旧版本 RC.5

您可以像这样利用 DomSanitizationService:

export class YourComponent {
  url: SafeResourceUrl;
  constructor(sanitizer: DomSanitizationService) {
    this.url = sanitizer.bypassSecurityTrustResourceUrl('your url');
  }
}

然后绑定到模板中的url:

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

不要忘记添加以下导入:

Don't forget to add the following imports:

import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';

Plunker 示例

这篇关于如何设置&lt;iframe src=“..."&gt;不会导致“不安全值"异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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