Electron: dialog.showMessageBox() not working with a parent window (modal failed)

Viewed 1399

I'm learning Electron and trying very basic things... without success.

Whatever the technique I use to make a dialog box modal, it fails. Either the dialog box is not modal, or the dialog box is empty (...and still not modal).

const {BrowserWindow, dialog} = require('electron')

dialog.showMessageBoxSync(BrowserWindow.getFocusedWindow(), {message: "FooBar"});
// Not modal: BrowserWindow.getFocusedWindow() returns null.

dialog.showMessageBoxSync(BrowserWindow.getAllWindows()[0], {message: "FooBar"});
// Not modal: BrowserWindow.getAllWindows() returns an empty array.

dialog.showMessageBoxSync(parentWindow, {message: "FooBar"});
// "parentWindow" comes from the "click" handler of the menu item launching the message box: it is not null.
// Error: the message box is not modal, and does not display "FooBar" (i.e. it is empty).

This code is called from the main process, and no error is displayed in the terminal or the development tools. The outcome is the same if I use dialog.showMessageBox() instead of showMessageBoxSync().

Electron: v9.0.5 on Windows 10 (x64).

2 Answers

dialog.showMessageBoxSync accepts 2 arguments in which first one is optional. so even if it is null or undefined it'll work without it. so every dialog module method works only works after app is ready.

so make sure you are calling it after app is ready.

app.on('ready', () => {
  // create window call

  // your code

  dialog.showMessageBoxSync(BrowserWindow.getFocusedWindow(), {message: "FooBar"});

  dialog.showMessageBoxSync(BrowserWindow.getAllWindows()[0], {message: "FooBar"});
})

or any other ready listen way will work. like app.whenReady().

Related