How to detect close in another domain of iframe?

by mallory_cormier , in category: Javascript , a month ago

How to detect close in another domain of iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , a month ago

@mallory_cormier 

To detect when an iframe is closed from within another domain, you can use the postMessage method to communicate between the parent window and the iframe window. Here's how you can do it:

  1. In the parent window, add an event listener to listen for messages from the iframe window:
1
2
3
4
5
window.addEventListener('message', function(event) {
  if (event.data === 'iframeClosed') {
    // Do something when iframe is closed
  }
});


  1. In the iframe window, when the iframe is closed, send a message to the parent window:
1
2
3
window.onbeforeunload = function() {
  parent.postMessage('iframeClosed', '*');
}


By using postMessage, you can securely communicate between the parent window and the iframe window even if they are on different domains. Make sure to replace '*' with the correct URL of the parent window if it is on a different domain.