【问题标题】:Angular2 iframe not workingAngular2 iframe 不工作
【发布时间】:2018-03-21 10:32:20
【问题描述】:

我正在尝试在 Angular2 上加载 iFrame。但是地址是动态加载的。

实时代码是:https://angular-fgzjog.stackblitz.io

在 app.coponent.ts 内

<!-- this works -->
    <p>
     iframe address  : {{iFrameSrc}} 
    </p>

<!--- this does not work -->
    <div class="embed-responsive embed-responsive-16by9">
                    <iframe class="embed-responsive-item" [src]="iFrameSrc"></iframe> 
                  </div>

【问题讨论】:

标签: angular iframe angular5


【解决方案1】:

Angular 正在清理您尝试放入 iframe src 的任何内容,以防止不安全的内容。因此你必须清理你的 url 以告诉 Angular 你是故意添加这个 url 并且它是安全的!

https://angular.io/api/platform-browser/DomSanitizer

所以要么将此逻辑添加到您的组件并调用:

constructor(
 private domSanitizer: DomSanitizer, 
 // ...
) // ...

this.safeiFrameSrc = this.domSanitizer.bypassSecurityTrustUrl(this.iFrameSrc)


<!-- template binding: -->
<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" [src]="safeiFrameSrc"></iframe> 
</div>

或者你也可以创建一个管道:

@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  constructor(protected sanitizer: DomSanitizer) {}

  transform(value: string, type: string = 'url'): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html':
        return this.sanitizer.bypassSecurityTrustHtml(value);
      case 'style':
        return this.sanitizer.bypassSecurityTrustStyle(value);
      case 'script':
        return this.sanitizer.bypassSecurityTrustScript(value);
      case 'url':
        return this.sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl':
        return this.sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        throw new Error(`Unable to bypass security for invalid type: ${type}`);
    }
  }
}

<!-- usage: -->

<div class="embed-responsive embed-responsive-16by9">
  <iframe class="embed-responsive-item" [src]="iFrameSrc | safe"></iframe> 
</div>    

这应该可以解决问题!

【讨论】:

  • 很好,很高兴听到!只是在直接输出 url 时看到错误,这只是 Angular 的意图告诉您,您只应该在绑定中使用它,因为它声明不要直接在某处公开安全 url!但是,这只是一个旁注,无论如何我认为你不想在生产中这样做! :)
猜你喜欢
  • 1970-01-01
  • 2017-12-15
  • 2016-04-02
  • 2017-04-12
  • 2017-11-23
  • 2017-03-03
  • 2016-08-15
相关资源
最近更新 更多