我正在编写一个涉及iframe src属性设置的教程:
iframe
src
<iframe width="100%" height="300" src="{{video.url}}"></iframe>
这会引发异常:
Error: unsafe value used in a resource URL context at DomSanitizationServiceImpl.sanitize...
我已经尝试过使用绑定[src]但没有成功。
[src]
更新 v8
以下答案有效,但会使您的应用程序面临 XSS 安全风险!. this.domSanitizer.bypassSecurityTrustResourceUrl(url)建议使用而不是使用this.domSanitizer.sanitize(SecurityContext.URL, url)
this.domSanitizer.bypassSecurityTrustResourceUrl(url)
this.domSanitizer.sanitize(SecurityContext.URL, url)
更新
对于RC.6^版本,使用DomSanitizer
plunker
一个不错的选择是为此使用纯管道:
import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer} from '@angular/platform-browser'; @Pipe({ name: 'safe' }) export class SafePipe implements PipeTransform { constructor(private domSanitizer: DomSanitizer) {} transform(url) { return this.domSanitizer.bypassSecurityTrustResourceUrl(url); } }
记得将你的 new 添加SafePipe到 AppModule 的declarations数组中。(如文档所示)
SafePipe
declarations
@NgModule({ declarations : [ ... SafePipe ], })
html
<iframe width="100%" height="300" [src]="url | safe"></iframe>
如果您使用embed标签,这对您来说可能很有趣:
embed
我想应该是:
this.pdfUrl = this.domSanitizer.bypassSecurityTrustResourceUrl('url')
并像这样使用它:
<iframe [src]="pdfUrl" width="500" height="600" type='application/pdf'></iframe>
见Plunkr
更新(embedChrome 中存在标签错误)
对于embed标签,您可以通过以下方式重新注入嵌入标签outerHTML:
outerHTML
this.renderer.setElementProperty(el, 'outerHTML', el.outerHTML)
请参阅此案例的plunker
old version RC.5
你可以DomSanitizationService这样利用:
DomSanitizationService
export class YourComponent { url: SafeResourceUrl; constructor(domSanitizationService: DomSanitizationService) { this.url = domSanitizer.bypassSecurityTrustResourceUrl('your url'); } }
然后绑定到url您的模板中:
url
<iframe width="100%" height="300" [src]="url"></iframe>
不要忘记添加以下导入:
import { SafeResourceUrl, DomSanitizationService } from '@angular/platform-browser';
Plunker sample