How to Use Electron's Native Dialog APIs: messageBox and errorBox

Electron exposes native system dialogs through the dialog module, providing both asynchronous showMessageBox() and synchronous showMessageBoxSync() for custom alerts, plus showErrorBox() for fatal error reporting before the app is ready.

The electron/electron repository implements these APIs in lib/browser/api/dialog.ts, which serves as the JavaScript façade that validates arguments, normalizes platform-specific options, and delegates to C++ bindings. Understanding the architecture and proper use of these methods ensures your desktop application presents native-looking dialogs that respect platform conventions while maintaining responsive UI behavior.

Architecture of the dialog Module

JavaScript API Layer

The public interface lives in lib/browser/api/dialog.ts, exporting showMessageBox(), showMessageBoxSync(), and showErrorBox() as the primary entry points. Every method first invokes checkAppInitialized() to verify the Electron app has emitted the ready event; if called too early, the function throws an error immediately【/cache/repos/github.com/electron/electron/main/lib/browser/api/dialog.ts#L54-L58】.

For showMessageBox calls, the code normalizes button labels through normalizeAccessKey() to handle platform-specific accelerator keys—stripping & symbols on macOS, converting them to underscores on Linux, and preserving Windows-style access keys【/cache/repos/github.com/electron/electron/main/lib/browser/api/dialog.ts#L31-L52】.

Native Binding Layer

After validation, the module accesses the native implementation via process._linkedBinding('electron_browser_dialog'), storing it as dialogBinding. The JavaScript layer constructs a plain settings object and invokes the corresponding binding method—either dialogBinding.showMessageBox(), dialogBinding.showMessageBoxSync(), or dialogBinding.showErrorBox()【/cache/repos/github.com/electron/electron/main/lib/browser/api/dialog.ts#L4-L12】【/cache/repos/github.com/electron/electron/main/lib/browser/api/dialog.ts#L34-L40】.

Synchronous vs. Asynchronous Flows

Every dialog method offers both sync and async variants:

  • Asynchronous (showMessageBox): Returns a Promise that resolves with the user's selection, keeping the Node.js event loop unblocked.
  • Synchronous (showMessageBoxSync): Calls dialogBinding.showMessageBoxSync() and blocks the process until the user dismisses the dialog【/cache/repos/github.com/electron/electron/main/lib/browser/api/dialog.ts#L34-L40】.

Using showMessageBox and showMessageBoxSync

Asynchronous Message Boxes (Non-Blocking)

Use dialog.showMessageBox() for interactive workflows where your application must continue processing after the user clicks a button. This method accepts an optional BrowserWindow reference as the first argument (to parent the dialog) and an options object.

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

async function confirmDelete() {
  const mainWindow = BrowserWindow.getFocusedWindow();

  const result = await dialog.showMessageBox(mainWindow, {
    type: 'warning',
    buttons: ['Delete', 'Cancel'],
    defaultId: 1,
    cancelId: 1,
    title: 'Delete File',
    message: 'Are you sure you want to delete this file?',
    detail: 'This action cannot be undone.'
  });

  if (result.response === 0) {
    console.log('File will be deleted');
  } else {
    console.log('Delete cancelled');
  }
}

The implementation path flows from showMessageBox → messageBox(false, …) → dialogBinding.showMessageBox(), where the boolean false indicates non-blocking execution【/cache/repos/github.com/electron/electron/main/lib/browser/api/dialog.ts#L56-L78】.

Synchronous Message Boxes (Blocking)

Use showMessageBoxSync() for CLI-style scripts or early initialization code where the execution flow must pause until the user responds. This method returns the zero-based index of the clicked button directly.

const { dialog } = require('electron');

const choice = dialog.showMessageBoxSync({
  type: 'question',
  buttons: ['Yes', 'No'],
  title: 'Proceed?',
  message: 'Do you want to continue?'
});

if (choice === 0) {
  console.log('User said Yes');
} else {
  console.log('User said No');
}

This calls messageBox(true, …) internally, triggering dialogBinding.showMessageBoxSync() which blocks the main thread until the native dialog closes【/cache/repos/github.com/electron/electron/main/lib/browser/api/dialog.ts#L72-L80】.

Platform-Specific Access Key Normalization

When specifying button labels with ampersands (e.g., '&Save'), Electron automatically adapts the presentation:

  • Windows: Displays as "Save" with the "S" underlined as an Alt shortcut.
  • Linux: Converts to "S_ave" with underlined access key.
  • macOS: Strips the ampersand entirely, displaying "Save" without keyboard shortcut indicators【/cache/repos/github.com/electron/electron/main/lib/browser/api/dialog.ts#L31-L52】.

Using showErrorBox for Fatal Errors

The showErrorBox() method provides a synchronous, no-frills alert for reporting critical failures. Unlike showMessageBox, it accepts only a title and content string, offering no customization of buttons or icons. This method is specifically designed for scenarios where the application has not yet emitted the ready event or when you must display an error before the full dialog subsystem initializes.

const { dialog } = require('electron');

// Safe to call during early startup
dialog.showErrorBox('Initialization Failed', 'Unable to load configuration file.');

The implementation directly forwards arguments to dialogBinding.showErrorBox() without the validation or normalization steps required by message boxes【/cache/repos/github.com/electron/electron/main/lib/browser/api/dialog.ts#L89-L91】.

Attaching Dialogs to Parent Windows

Supplying a BaseWindow or BrowserWindow instance as the first argument to showMessageBox() creates a modal relationship. On macOS, this presents the dialog as a sheet attached to the window title bar; on Windows and Linux, it creates a modal window that blocks input to the parent until dismissed【/cache/repos/github.com/electron/electron/main/docs/api/dialog.md#L81-L84】.

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

const win = new BrowserWindow({ width: 800, height: 600 });

dialog.showMessageBox(win, {
  type: 'info',
  buttons: ['OK'],
  title: 'Welcome',
  message: 'Welcome to the app!'
});

Summary

  • Import path: All native dialog methods reside in require('electron').dialog, implemented in lib/browser/api/dialog.ts.
  • Async vs. Sync: Use showMessageBox() for non-blocking UI workflows; use showMessageBoxSync() when you must pause execution and wait for user input.
  • Error handling: Use showErrorBox() for pre-ready fatal errors, as it bypasses the app.isReady() check and requires no complex options.
  • Window parenting: Pass a BrowserWindow reference to create platform-native modal dialogs (sheets on macOS, modal windows on other platforms).
  • Platform parity: The normalizeAccessKey() function automatically handles button accelerator keys (&) according to macOS, Linux, and Windows conventions.

Frequently Asked Questions

What is the difference between showMessageBox and showErrorBox in Electron?

showMessageBox supports customizable buttons, icons, and detailed messages, returning the user's selection either via Promise (async) or integer (sync). showErrorBox accepts only a title and content string, always runs synchronously, and is designed specifically for displaying fatal errors before the application has fully initialized, as it bypasses the standard app-ready validation.

Can I use Electron's dialog APIs before the app is ready?

Only showErrorBox() can be called before the ready event. All showMessageBox variants (sync and async) invoke checkAppInitialized(), which throws an error if the app has not yet emitted ready【/cache/repos/github.com/electron/electron/main/lib/browser/api/dialog.ts#L54-L58】.

How do I make a dialog modal to a specific window in Electron?

Pass the BrowserWindow instance as the first argument to showMessageBox(). For example: dialog.showMessageBox(mainWindow, options). This attaches the dialog as a sheet on macOS and a modal window on Windows/Linux, preventing interaction with the parent window until the dialog closes【/cache/repos/github.com/electron/electron/main/docs/api/dialog.md#L81-L84】.

Where are the native dialog implementations located in the Electron source code?

The JavaScript API layer is in lib/browser/api/dialog.ts, which calls into the C++ binding via process._linkedBinding('electron_browser_dialog'). Platform-specific native code for Windows resides in shell/browser/ui/win/dialog_thread.cc and dialog_thread.h, while macOS and Linux implementations are handled in corresponding platform directories within shell/browser/ui/.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →