Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger an event in React after an opened window closes

I have a div in React with an onClick handler that when clicked implements window.open in a pop-up window that directs them to an external URL. When the user closes the pop-up window, I would like to implement an API call. However, everything I've tried has failed, including attempting to use event listeners.

How can I detect when a window is closed in React?

The current code I have for the window event is as follows:

export class App extends Component {

  opener = () => {
    const myWindow = window.open("https://www.espn.com", "MsgWindow", "width=200,height=100");
  }

  render() {  

    return (
      <div onClick={this.opener}>
        Hello World
      </div>
    );
  }
}
like image 808
Dog Avatar asked Sep 02 '25 09:09

Dog


1 Answers

You could change the opener function as below:

  opener = () => {
    const myWindow = window.open("https://www.espn.com", "MsgWindow", "width=200,height=100");

    var timer = setInterval(function() { 
        if(myWindow.closed) {
            clearInterval(timer);
            alert('closed');
        }
    }, 1000);
  }

Reference | Codepen

like image 144
ibex Avatar answered Sep 04 '25 21:09

ibex