Prevent Window from Closing


#1

I am using React for my electron app and am trying to prevent the window from closing under certain conditions. As given in the documentation, I am using the “beforeunload” event to attach an event handler. Here I ask the user using the dialog api whether she wants to quit the application. But no matter which button is clicked, the window closes. The relevant code of the Main.react component is as follows:

onUnload:Function = (evt) =>{
    const dialogOptions = {
      type: 'warning',
      buttons: ['Yes','No'],
      defaultId: 1,
      title: Quit Application?',
      message:'Do you want to save your work and close the application?',
      cancelId: 1,
    };

    const clickedButtonIndex = dialog.showMessageBox(dialogOptions);
    console.log("clickedButtonIndex:%s", clickedButtonIndex);
    if (clickedButtonIndex === 1) {
        evt.returnValue = false;
    } else {
      evt.returnValue = undefined;
    }
  };

componentDidMount() {
    window.addEventListener('beforeunload', this.onUnload);
  }

  componentWillUnmount() {
    window.removeEventListener('beforeunload', this.onUnload);
  }

The strange thing is that if I open the developer tools, then I see the window does not close at all and when the developer tools are closed, the window closes irrespective of what I click. In the developer tools I see that the values are being set correctly.