使用 angular 检测对 iframe 的点击

detect click into iframe using angular

我想在用户单击弹出窗口外部时关闭多 select 下拉弹出窗口。当用户在 IFrame 外部单击时,它工作正常。但是当用户点击 iframe 弹出窗口时并没有关闭。我正在尝试添加一些补丁代码,但为此我需要检测 Iframe 上的点击事件。例子看多了都没有很好的解决办法

 @HostListener('click', ['$event.target'])
  onClick() {
    console.log('iframe clicked');
 }

我试过上面的代码,但是 onClick 方法没有调用 iframe 点击。

注意:我需要检测每个点击事件,而不仅仅是第一次点击。

您可以试试这个 Angular 指令:

import {
  Directive,
  ElementRef,
  OnInit,
  Renderer2,
  Input,
  Output,
  EventEmitter,
  HostListener
} from '@angular/core';

@Directive({
  selector: '[appIframeTracker]'
})
export class IframeTrackerDirective implements OnInit {
  private iframeMouseOver: boolean;

  @Input() debug: boolean;

  @Output() iframeClick = new EventEmitter<ElementRef>();

  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngOnInit(): void {
    this.renderer.listen(window, 'blur', () => this.onWindowBlur());
  }

  @HostListener('mouseover')
  private onIframeMouseOver() {
    this.log('Iframe mouse over');
    this.iframeMouseOver = true;
    this.resetFocusOnWindow();
  }

  @HostListener('mouseout')
  private onIframeMouseOut() {
    this.log('Iframe mouse out');
    this.iframeMouseOver = false;
    this.resetFocusOnWindow();
  }

  private onWindowBlur() {
    if (this.iframeMouseOver) {
      this.log('WOW! Iframe click!!!');
      this.resetFocusOnWindow();
      this.iframeClick.emit(this.el);
    }
  }

  private resetFocusOnWindow() {
    setTimeout(() => {
      this.log('reset focus to window');
      window.focus();
    }, 100);
  }

  private log(message: string) {
    if (this.debug) {
      console.log(message);
    }
  }
}

当我们点击 IFrame 时它会发出一个输出事件。

来源:https://gist.github.com/micdenny/db03a814eaf4cd8abf95f77885d9316f

希望对您有所帮助。