Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2 handle click on link inside iframe

Is there a way to catch a click on a link inside an iframe?

<iframe *ngIf="currentFrameUrl" id="contentFrame" [src]="currentFrameUrl | safe"></iframe>

My iframe component contains just a simple code which subscribes to observable variables.

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

My goal is to to catch click event on iframe link, stop its propagation and set the url of the iframe link using either router.navigate or location.go/location.replaceState. Not sure yet which option is better.

I have no control over the pages loaded inside the iframe. I only know, that the links should contains such url that can be used with my dynamic routes.

like image 302
mat.hudak Avatar asked Oct 17 '22 11:10

mat.hudak


1 Answers

use @HostListener('window:blur', ['$event']) decorator, method attached with this decorator trigger on IFrame click.

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

Note: Also this will work for cross-domain operations.

like image 67
s sharif Avatar answered Oct 20 '22 04:10

s sharif