角度2手柄单击iframe内的链接

dal*_*ows 5 html iframe typescript angular

有没有办法吸引点击链接iframe

<iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe"></iframe>
Run Code Online (Sandbox Code Playgroud)

我的iframe组件仅包含订阅可观察变量的简单代码。

export class ContentFrameComponent implements OnInit {
    currentFrameUrl: string;
    currentMenuState: boolean;
    @ViewChild('contentFrame') iframe: ElementRef;

    constructor(private frameService: ContentFrameService) {        
      this.currentMenuState = true;      
    }

    ngOnInit(): void {
      this.frameService.providerCurrentUrl$.subscribe(data => this.currentFrameUrl = data);
      this.frameService.providerMenuState$.subscribe(data => this.currentMenuState = data);
    }

    ngAfterViewInit() {
      let doc = this.iframe.nativeElement.contentDocument ||this.iframe.nativeElement.contentWindow;
      if (typeof doc.addEventListener !== undefined) {
        console.log("inside if - addEventListener") // Is shown
        doc.addEventListener("click", this.iframeClickHandler, false)
      } else if (typeof doc.attachEvent !== undefined) {
        console.log("inside if - attachEvent ") // Does not show
        doc.attachEvent("onclick", this.iframeClickHandler)
      }
    }

    iframeClickHandler(): void {
      console.log("Click test") // Does not show
    }
}
Run Code Online (Sandbox Code Playgroud)

我的目标是捕获iframe链接上的click事件,停止其传播并使用router.navigatelocation.go/ 设置iframe链接的url location.replaceState。尚不确定哪个选项更好。

我无法控制中加载的页面iframe。我只知道,链接应包含url可用于我的动态路线的链接。

s s*_*rif 5

使用 @HostListener('window:blur', ['$event']) 装饰器,此装饰器附加的方法在 IFrame 单击时触发。

  @HostListener('window:blur', ['$event'])
  onWindowBlur(event: any): void {
    console.log('iframe clicked');
  }
Run Code Online (Sandbox Code Playgroud)

注意:这也适用于跨域操作。


Max*_*x K -2

为什么不能使用简单的onclick?

试试这个代码:

<iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe" (onclick)="clicked()"></iframe>
Run Code Online (Sandbox Code Playgroud)

点击了