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

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

这会抛出一个异常:

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

我已经尝试使用[src]绑定,但没有成功。


当前回答

祝贺!¨^ ^ 我有一个简单有效的解决方案给你,是的!

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

[attr。Src]而不是Src ”视频。而不是{{video.url}}

伟大的,)

其他回答

这样我就可以使用Angular 5.2.0了

fileName.Component.ts

import { Component, OnInit, Input } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';

@Component({
  selector: 'app-sample',
  templateUrl: './fileName.component.html',
  styleUrls: ['./fileName.component.scss']
})

export class FileName implements OnInit {
  @Input()
  url: string = "https://www.mmlpqtpkasjdashdjahd.com";
  urlSafe: SafeResourceUrl;

  constructor(public sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.urlSafe= this.sanitizer.bypassSecurityTrustResourceUrl(this.url);
  }

}

fileName.Component.html

<iframe width="100%" height="100%" frameBorder="0" [src]="urlSafe"></iframe>

伙计们,就这些!!

祝贺!¨^ ^ 我有一个简单有效的解决方案给你,是的!

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

[attr。Src]而不是Src ”视频。而不是{{video.url}}

伟大的,)

constructor(
 public sanitizer: DomSanitizer, ) {

 }

我已经挣扎了4个小时。问题出在img标签。当你使用方括号的'src' ex: [src]。你不能使用这个角表达式{{}}。你只要直接从下面的实物例子给出。如果你给出角表达式{{}}。你会得到插值误差。

首先,我用ngFor来迭代国家 *ngFor="让国家中的国家" 然后你把这个放到img标签里。就是它了。 < img (src) = " sanitizer.bypassSecurityTrustResourceUrl (country.flag)” Height ="20" width="20" alt=""/> .

这对我很有用

我在iframe中定义了一个id

<iframe id="embeddedPage"></iframe>

在组件中,我使用了这段代码

export class YourComponent implements OnInit {
    
  constructor() {}

  ngOnInit(): void {
    const iframe =  document.getElementById('embeddedPage') as HTMLIFrameElement;
    iframe.contentWindow.location.replace('your url');
  }

}

我将分享这个解决方案,即使这不是最佳实践,但它发生在我身上,我们不允许使用this. domsaniizer . bypasssecuritytrustresourceurl (url)解决方案,因为一个自动安全警告停止了CI/CD管道。

@Component({
  template: '<iframe #iframeRef></iframe>'
})
export class UnsafeUrlBypassIframeSampleComponent implements AfterViewInit {
  @ViewChild('iframeRef') iframe: ElementRef<HTMLIFrameElement>;
  
  constructor(private renderer: Renderer2) {}
  
  ngAfterViewInit() {
    const MY_UNSAFE_URL = '/path/to/something';
    this.renderer.setProperty(this.iframe.nativeElement, 'src', MY_UNSAFE_URL);
  }
}

如果你确实需要绕过Angular的安全系统,而这将不可避免地导致漏洞,那么最好明确地这样做。