Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dialog.showMessageBox not returning button index in electron main.js

I have a messagebox that will open when the user click close on dashboardWindow (X button top right on windows os)

dashboardWindow.on("close", (event) => {
    event.preventDefault();
    console.log("before message box");
    dialog.showMessageBox(
      dashboardWindows,
      {
        message: "Test",
        buttons: ["Default Button", "Cancel Button"],
        defaultId: 0, // bound to buttons array
        cancelId: 1 // bound to buttons array
      },
      (response) => {
        if (response === 0) {
          // bound to buttons array
          console.log("Default button clicked.");
        } else if (response === 1) {
          // bound to buttons array
          console.log("Cancel button clicked.");
        }
      }
    );
    console.log("after message box");
  });
}

The messagebox opened when i close the dashboardWindow but i can't get response === 0 to work. Samehow console.log("after message box"); already run even when there is no click on the buttons. How I can make the response work (return index button on messageBox)?

log on window close

like image 923
Wahid Feb Avatar asked Dec 05 '22 09:12

Wahid Feb


1 Answers

Please refer to the most recent API doc about dialog.showMessageBox: this method returns a Promise object and doesn't make use of a callback function any more, like it used to until Electron v5.x.x.

Returns Promise<Object> - resolves with a promise containing the following properties:

  • response Number - The index of the clicked button.
  • checkboxChecked Boolean - The checked state of the checkbox if checkboxLabel was set. Otherwise false.

This should work then (untested in your context though):

dashboardWindow.on("close", (event) => {
    event.preventDefault();
    console.log("before message box");
    dialog.showMessageBox(
      dashboardWindows,
      {
        message: "Test",
        buttons: ["Default Button", "Cancel Button"],
        defaultId: 0, // bound to buttons array
        cancelId: 1 // bound to buttons array
      })
      .then(result => {
        if (result.response === 0) {
          // bound to buttons array
          console.log("Default button clicked.");
        } else if (result.response === 1) {
          // bound to buttons array
          console.log("Cancel button clicked.");
        }
      }
    );
    console.log("after message box");
  });
like image 69
Joseph Baker Avatar answered Jan 12 '23 00:01

Joseph Baker