JavaScript

The dialog.showMessageBox() in Electron

A dialog box is a small window that communicates information to the user and prompts them for a response. Electron’s dialog.showMessageBox() is a customizable dialog box. You can provide a list of button labels to the buttons array and a checkbox with the given label.

Electron dialog.showMessageBox

Syntax:

dialog.showMessageBox([browserWindow, ]options[, callback])

The dialog.showMessageBox returns index of the clicked button, if a callback function is provided it returns undefined.

browserWindow:
The optional BrowserWindow argument allows the dialog to attach itself to a parent window, making it modal. i.e. from main.js the WIN = new BrowserWindow({width: 800, height: 600}). The WIN represents the BrowserWindow and can be use when invoking the dialog.showMessageBox method.

options:
An object to customize the message box. for example:

let options  = {
 buttons: ["Yes","No","Cancel"],
 message: "Do you really want to quit?"
}

An options object should at least contain the buttons and message properties. The buttons and message properties are mandatory. We'll discuss the options object later after showing some basic examples.

callback:
The optional callback function for asynchronous processing. Callback function has two parameters response (the index of the button that was clicked) and checkboxChecked (the checked state of the checkbox if checkboxLabel was set in options object).

Example 1: synchronous confirmation message box

First, create options object with required properties:

//Minimum options object
let options  = {
 buttons: ["Yes","No","Cancel"],
 message: "Do you really want to quit?"
}

Next, pass the options object to showMessageBox method to display confirmation box:

//Synchronous usage
let response = dialog.showMessageBox(options)
console.log(response)

The above example blocks the Process as we've not provided a callback function. It returns the index of the clicked button (0 for Yes, 1 for No and 2 for Cancel).

The browserWindow argument makes the confirmation box to remain "alway on top" when invoked, for example, we can use the WIN from the main.js code snippet: WIN = new BrowserWindow({width: 800, height: 600}):

//Synchronous modal - stay alway on top
let response = dialog.showMessageBox(WIN, options)
console.log(response)

Example 2: asynchronous confirmation message box

If a callback function is passed, the dialog will not block the process. The API call will be asynchronous and the result will be passed via callback(response) or callback(response, checkboxChecked) if checkboxLabel provided in the options object:

//asynchronous
//dialog.showMessageBox(options, (response) => {
dialog.showMessageBox(options, (response, checkboxChecked) => {
 console.log(response)
 console.log(checkboxChecked) //true or false
})

Asynchronous always on top modal:

//aSynchronous modal - stay alway on top
dialog.showMessageBox(WIN, options, (response, checkboxChecked) => {
 console.log(response)
 console.log(checkboxChecked) //true or false
})

Options object for dialog.showMessageBox

  • buttons:
    Array of texts for buttons i.e. ["Yes","No", "Cancel"]
  • message:
    Content of the message box.
  • detail :
    Extra information of the message.
  • defaultId:
    Index of the button in the buttons array which will be selected by default when the message box opens. The defaultId: 2 selects the Cancel button from the ["Yes","No", "Cancel"] buttons array.
  • title:
    Title of the message box.
  • type:
    Type of the message box, can be none, info, error, question or warning to show respective icon unless you set an icon using the icon option.
  • checkboxLabel:
    If provided, the message box will include a checkbox with the given label. The checkbox state can be inspected only when using callback function.
  • checkboxChecked:
    Initial checked state of the checkbox. false by default.
  • icon:
    The image path to show custom icon on message box.
  • cancelId:
    The index of the button to be used to cancel the dialog, via the Esc key. By default this is assigned to the first button.
  • noLink:
    Set it true if you don't want the dialog to appear in the style of modern Windows apps:
    Electron message box as modern app
  • normalizeAccessKeys:
    Set it true to enable Alt key shortcuts for buttons. Also add & character to buttons as shown below:
    /*old values
    buttons: ["Yes","No", "Cancel"]*/
    
    buttons:["&Yes","&No", "&Cancel"]

    The button &Yes can be selected via Alt-Y, &No can be selected via Alt-N and &Cancelcan be selected via Alt-C. The & will not show on button labels.

Let's create a more detailed confirmation box app.

Show conformation box when a user want to close window

In the following example, we listen for the BrowserWindow's close event inside the createWindow function. We prompt the user to confirm if he/she really want to close the current window. Based on the user's response, we either prevent the window from closing or close the window.

First we create a new Node project (see how to create a new Node project to generate package.json file):

  • Open command prompt / cli / shell and create message-box directory, for example on my Windows 10 PC:
  • D:\>mkdir message-box
  • D:\>cd message-box
  • Inside the message-box folder write npm init command and follow the wizard to generate package.json file (write main.js when npm wizard ask for entry point)
  • Write npm install electron --save-dev command to install Electron module
  • Open a code editor and create an empty index.html
    file (or use basic html tags), we’ll write the code later if needed
  • Create main.js file (see how to make desktop apps using Electron) and write the following code:

Electron dialog.showMessageBox() example from the main process

//main.js or index.js (if you've not changed the default entry point)

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

function createWindow () {
 WIN = new BrowserWindow({width: 800, height: 600})
 WIN.loadFile('index.html')

 WIN.on('closed', () => {
  WIN = null
 })

 //Listen close event to show dialog message box
 WIN.on('close', (event) => {

  //Cancel the current event to prevent window from closing
  event.preventDefault()

  //options object for dialog.showMessageBox(...)
  let options = {}

  //Can be "none", "info", "error", "question" or "warning".
  options.type = "question"

  //Array of texts for buttons.
  options.buttons = ["&Yes","&No","&Cancel"]

  //Index of the button in the buttons array which will be selected by default when the message box opens.
  options.defaultId = 2

  //Title of the message box
  options.title = "Multiple buttons on a message box"

  //Content of the message box
  options.message = "Do you really want to quit?"

  //More information of the message
  options.detail = "Press Yes button to quit"

  //Shows a checkbox
  options.checkboxLabel = "Checkbox only works with callback"

  //Initial checked state
  options.checkboxChecked = true

  //options.icon = "/path/image.png"

  //The index of the button to be used to cancel the dialog, via the Esc key
  options.cancelId = 2

  //Prevent Electron on Windows to figure out which one of the buttons are common buttons (like "Cancel" or "Yes")
  options.noLink = true

  //Normalize the keyboard access keys
  options.normalizeAccessKeys = true

  /*Syntax:
   dialog.showMessageBox(BrowserWindow, options, callback);
  */
  dialog.showMessageBox(WIN, options, (res, checked) => {
   if (res === 0){
    //Yes button pressed
    WIN.destroy()
   }
   else if (res === 1) {
    //No button pressed
   }
   else if (res === 2){
    //Cancel button pressed
   }
  })
  
 })
 /* End of BrowserWindow close event code */
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
 if (process.platform !== 'darwin') {
  app.quit()
 }
})

app.on('activate', () => {
 if (WIN === null) {
  createWindow()
 }
})

Electron dialog.showMessageBox() example from the renderer process

Since dialog module is only available to main process you can not directly include the dialog module in a renderer process. To display a confirmation box from the renderer process you need to use remote module. See how to use remote module in renderer process.

//renderer.js - the renderer process

const {remote} = require('electron')
const dialog   = remote.dialog

let WIN      = remote.getCurrentWindow()

WIN.on('close', (event) => {
 event.preventDefault()
 let options = {}
 options.buttons = ["&Yes","&No","&Cancel"]
 options.message = "Do you really want to quit?"
 
 dialog.showMessageBox(WIN, options, (res, checked) => {
  console.log(res)
  console.log(checked)
  if (res === 0)
   WIN.destroy()
 })
})
Advertisement:
Advertisement: