Is it possible to detect window.close from iframe?

Danilo Ruziska picture Danilo Ruziska · Aug 29, 2017 · Viewed 10.9k times · Source

I have a modal (a React component from my application), and inside it i have an iframe. I don't have control over the iframe, and I know it calls window.close after some action is taken. Is there a way to detect when the content inside the iframe called window.close, so I can also close the modal?

Important: I'm not using jQuery, only pure javascript.

iframe code:

      <iframe height='500' width='340'                      
        src='http://content_url'
        ref={(f) => { this.ifr = f; }}>
      </iframe>

with this ref, I can refer to the iframe from my react component:

  componentDidMount() {
    this.ifr.onload = () => {
      //whatever action
    };
  }

but I can't do what I want with the unload event, because the iframe is not unloaded, it just calls window.close inside it.

Thanks!

Answer

bennygenel picture bennygenel · Aug 29, 2017

You can try to set window.close to some other function and catch when the iframe calls it.

  var closing = window.close;
  window.close = function () {
    console.log('window close fired!');
    closing();
  };

Better way even creating event emitters.

  var event = new Event('onCloseWindow');

  // Listen for the event.
  elem.addEventListener('onCloseWindow', function (e) { ... }, false);

  var closing = window.close;
  window.close = function () {
    // Dispatch the event.
    elem.dispatchEvent(event);
    closing();
  };