2

I want to close multi-select drop-down popup when user click outside the popup. It's working fine when user click outside of IFrame. But when user click on iframe popup did't got closed. I am trying to add some patch code but for that I need to detect click event on Iframe. I seen too many example but did't got fine solution.

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

I have tried above code but onClick method didn't call on iframe click.

Note: I need to detect every click event not only first click.

1
  • You can't. The event occurs inside the iframe window instance not in parent window Commented Aug 1, 2019 at 13:11

1 Answer 1

6

You can try this Angular directive:

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);
    }
  }
}

It emits an output event when we click on IFrame.

Source: https://gist.github.com/micdenny/db03a814eaf4cd8abf95f77885d9316f

I hope it will help.

Sign up to request clarification or add additional context in comments.

2 Comments

As per my under standing it will call every time when mouse hover on iframe. But in my case I need to close multi-select popup on click event.
this doesnt work with youtube embed iframes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.