Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect an event from inside an iframe in Angular

Tags:

angular

I've created an Angular Material modal that loads an Iframe. In this Iframe there is a form. I would like to close the modal after submitting this form but since the form HTML is created through the Iframe URL, I cannot attached actions to the submit button.

<h3 matDialogTitle>My Dialog</h3>
<mat-dialog-content>
  <iframe 
    width="800" 
    height="400"
    frameBorder="0"
    [src]=" url | saferesource">
  </iframe>
</mat-dialog-content>
<mat-dialog-actions>
  <!-- <button md-button matDialogClose>Close Dialog</button> -->
</mat-dialog-actions>

How can I close this modal after clicking on submit button within the generated HTML form?

Thanks

like image 550
GreatHawkeye Avatar asked Oct 20 '25 13:10

GreatHawkeye


1 Answers

You can make use of the postMessage method on the Window object.

More info here: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Short example, in the iframe you can do:

window.parent.postMessage('close', '*');

And in the application hosting the iframe listen on this message:

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
{
  if (event.data === 'close'){
      // close dialog
  }
}

Note that this is pseudo code and not checked on syntax and actually working functionality.

like image 97
Sam Vloeberghs Avatar answered Oct 22 '25 04:10

Sam Vloeberghs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!