wrzr123
wrzr123

Reputation: 31

Detect click outside of Angular application which runs in an iframe

I'm developing an Angular App which is embedded in a Wordpress page. I'm using an iframe to embedd the Angular App into the Worpress page. Now I have modal dialogs in my Angular App which should be closed when clicking outside the dialogs. That works fine when the click happens outside the dialog and inside the Angular App. But when the click goes even outside the iframe, somewhere else on the wordpress page, nothing happens. It seems like all clicks outisde the iframe are not recognized by the Angular event handlers.
I've found some solutions for Javascript where the page outside of the iframe was referenced through document.parentElement. In my case that doesn't seem to work, the parentElement of my document is undefined.
I hope you understand what my problem is, it would be quite some effort to put up a running example.

Regards and thanks in advance!

Upvotes: 0

Views: 1080

Answers (2)

wrzr123
wrzr123

Reputation: 31

Thanks @Msk Satheesh and @MikeOne, with the hints of both of you guys combined I got it running!
The thing is that I can really address the (outer) wordpress page by window.parent. But this only works because both run in the same domain. Combined with the code Msk Satheesh posted in his first comment it works. And I don't even need to run anything outside of Angular. In my modal dialog component in Angular I put the following code:

  constructor(public dialogRef: MatDialogRef<ResultsDialogComponent>, private eRef: ElementRef) {}
  
  ngOnInit(): void {
    if(!this.onDocumentClickFunction){
      this.onDocumentClickFunction = this.onDocumentClick.bind(this);
    }
    window.parent.addEventListener( 'click', this.onDocumentClickFunction ); 
  }

  onDocumentClick() {    
    this.dialogRef.close();
    this.eRef.nativeElement.click();
  }

  ngOnDestroy() {
    window.parent.removeEventListener( 'click', this.onDocumentClickFunction ); 
  }

And that's it. The elegant thing is that the onDocumentClick() only fires if the click is outside the iFrame. That means I don't need additional logic to find out if the click is inside or outside the iFrame. The line this.eRef.nativeElement.click(); is necessary to bring back the focus to the iFrame. Without that line the modal only disappears if the user clicks into the iFrame himself.

Upvotes: 0

Msk Satheesh
Msk Satheesh

Reputation: 1536

Try Using:

Angular Component

   constructor(private zone:NgZone) {
       window['clickEvent'] = (event) => {
           zone.run(() => {
               console.log(event);
           });
       };
   }

Outer Js:

onClickEvent(event){
     window.parent.frames[#frameId].clickEvent(event);
}

Upvotes: -1

Related Questions