问题描述
我正在研究一个涉及设置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:
旧版本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>
别忘了添加以下导入:
import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';
Plunker sample
这篇关于如何设置< iframe src ="...">不会导致“不安全值"异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!