Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Windows, Menus and Tray

Context Menus and Native Dialogs in Electron

Add right-click context menus with Menu.popup, spelling suggestions and IPC, and use native dialogs: open, save, message boxes and error boxes, with safe patterns and runnable models.

Two small features make an app feel truly native: a right-click menu that offers the right actions for what you clicked, and native dialogs for opening files, saving them and asking questions. Both are rendered by the operating system, so they match the user's theme, language and accessibility settings automatically. Both also live in the main process, so the page asks for them through IPC.

Context menus

By default, right-clicking in an Electron window shows nothing. Web content decides whether to show a menu, and Electron does not add one. You build the menu in the main process and show it with menu.popup().

The usual flow has three steps:

  1. The page listens for the contextmenu event and tells the main process (through the preload API) what was clicked.
  2. The main process builds a Menu for that situation and calls popup.
  3. Menu items either act directly (copy, paste) or send a message back to the page.
JavaScript
// preload.js
contextBridge.exposeInMainWorld('api', {
  showItemMenu: (itemId) => ipcRenderer.send('context-menu:item', itemId),
  onItemAction: (cb) => {
    const l = (_e, action) => cb(action)
    ipcRenderer.on('item:action', l)
    return () => ipcRenderer.removeListener('item:action', l)
  },
})
JavaScript
// renderer
list.addEventListener('contextmenu', (event) => {
  const row = event.target.closest('[data-id]')
  if (!row) return
  event.preventDefault()
  window.api.showItemMenu(row.dataset.id)
})
window.api.onItemAction(({ id, action }) => { /* rename, delete... */ })
JavaScript
// main
const { ipcMain, Menu, BrowserWindow } = require('electron')

ipcMain.on('context-menu:item', (event, itemId) => {
  if (typeof itemId !== 'string') return
  const win = BrowserWindow.fromWebContents(event.sender)
  const menu = Menu.buildFromTemplate([
    { label: 'Rename', click: () => event.sender.send('item:action', { id: itemId, action: 'rename' }) },
    { label: 'Duplicate', click: () => event.sender.send('item:action', { id: itemId, action: 'duplicate' }) },
    { type: 'separator' },
    { label: 'Delete', click: () => event.sender.send('item:action', { id: itemId, action: 'delete' }) },
  ])
  menu.popup({ window: win })
})

popup() without coordinates shows the menu at the mouse cursor.

Text fields: copy, paste and spelling

Text inputs need the standard editing items. Electron emits a context-menu event on webContents with params describing the clicked thing: selected text, whether it is editable, misspelled word and suggestions, link URL, image source and more.

JavaScript
win.webContents.on('context-menu', (event, params) => {
  const items = []

  for (const suggestion of params.dictionarySuggestions) {
    items.push({ label: suggestion, click: () => win.webContents.replaceMisspelling(suggestion) })
  }
  if (params.misspelledWord) {
    items.push({ type: 'separator' })
  }
  if (params.isEditable) {
    items.push({ role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'selectAll' })
  } else if (params.selectionText) {
    items.push({ role: 'copy' })
  }
  if (params.linkURL.startsWith('https://')) {
    items.push({ label: 'Open link in browser', click: () => shell.openExternal(params.linkURL) })
  }

  if (items.length) Menu.buildFromTemplate(items).popup()
})

Each situation produces a different menu. This is just a decision table, and you can try it here: a function maps "what was clicked" to menu items. Test inputs show the output for several cases, including unsafe link schemes.

Node.js Stand-in: choose context menu items

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Native dialogs

The dialog module opens system dialogs. Pass the parent window as the first argument so the dialog is attached to it (a sheet on macOS, modal on Windows). All the useful methods return Promises:

Open

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

const { canceled, filePaths } = await dialog.showOpenDialog(win, {
  title: 'Open notes',
  defaultPath: app.getPath('documents'),
  filters: [
    { name: 'Markdown', extensions: ['md', 'markdown'] },
    { name: 'All Files', extensions: ['*'] },
  ],
  properties: ['openFile', 'multiSelections'],     // or 'openDirectory'
})
if (!canceled) console.log(filePaths)

Save

JavaScript
const { canceled, filePath } = await dialog.showSaveDialog(win, {
  defaultPath: 'untitled.md',
  filters: [{ name: 'Markdown', extensions: ['md'] }],
})

Message box and error box

JavaScript
const { response, checkboxChecked } = await dialog.showMessageBox(win, {
  type: 'warning',                       // 'none', 'info', 'error', 'question', 'warning'
  title: 'Unsaved changes',
  message: 'Save changes to "report.md" before closing?',
  detail: 'Your changes will be lost if you do not save them.',
  buttons: ['Save', "Don't Save", 'Cancel'],
  defaultId: 0,                          // Enter key
  cancelId: 2,                           // Escape key and the window close button
  checkboxLabel: 'Do this for all files',
})
// response is the index of the clicked button

dialog.showErrorBox('Could not open file', 'The file is damaged.')   // blocking, simple

Always set cancelId, so pressing Escape means what the user expects. Put the destructive choice on a button that is not the default.

Security: the main process should choose paths

A path returned from showOpenDialog was chosen by the user in a native UI that the page cannot fake. Keep that path in the main process (or store an opaque id) and let the page refer to it by id. Do not accept a free-form path from the page later. The following stand-in models a "file handle" registry: the dialog result is stored under a token, and only tokens work from the page.

Node.js Stand-in: dialog results become tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The page never sends a path back, so a compromised page cannot ask for /etc/passwd.

Sync versus async dialog methods

Older code uses dialog.showOpenDialogSync and showMessageBoxSync. They block the main process until the user answers, freezing every window. Prefer the Promise versions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you build and show a context menu in Electron?

    Menu lives in the main process; the page reports the right-click and the main process pops up the menu.
  2. 2. Why pass the parent window to dialog.showOpenDialog(win, options)?

    With a parent window the dialog is modal to it and appears properly attached on each platform.
  3. 3. What is the benefit of cancelId in showMessageBox?

    Without cancelId, closing the dialog returns an unexpected index; set it to the safe Cancel button.
  4. 4. Why avoid dialog.showOpenDialogSync?

    Sync dialogs block the main event loop; use the Promise-based methods.

Summary

  • Context menus are built in the main process and shown with popup; the context-menu event provides details like selected text and spelling suggestions.
  • Use role items for cut, copy, paste and select all.
  • dialog.showOpenDialog, showSaveDialog and showMessageBox are async; always pass the parent window and set cancelId.
  • Keep user-chosen paths in the main process and give the page opaque handles.

Next: Tray Icons and Notifications