Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Windows, Menus and Tray

Application Menus, Accelerators and Global Shortcuts

Build native application menus in Electron with Menu.buildFromTemplate, roles, accelerators, checkboxes and radio items, handle macOS differences, and register global shortcuts. Runnable template models.

A menu bar is one of the clearest signs of a real desktop app. Users expect File, Edit and View menus, keyboard shortcuts such as Ctrl+S, and the standard copy and paste commands to work. Electron builds native menus from a plain JavaScript description, so you get the look and behavior of each operating system for free.

Menus belong to the main process (the Menu module is not available in renderers). When a menu item needs the page to do something, it sends a message with webContents.send.

A first menu

JavaScript
const { app, Menu, BrowserWindow, shell } = require('electron')
const isMac = process.platform === 'darwin'

const template = [
  ...(isMac ? [{ role: 'appMenu' }] : []),
  {
    label: 'File',
    submenu: [
      {
        label: 'New',
        accelerator: 'CmdOrCtrl+N',
        click: () => BrowserWindow.getFocusedWindow()?.webContents.send('menu:new'),
      },
      { type: 'separator' },
      isMac ? { role: 'close' } : { role: 'quit' },
    ],
  },
  { role: 'editMenu' },
  { role: 'viewMenu' },
  { role: 'windowMenu' },
  {
    role: 'help',
    submenu: [
      { label: 'Documentation', click: () => shell.openExternal('https://example.com/docs') },
    ],
  },
]

app.whenReady().then(() => {
  Menu.setApplicationMenu(Menu.buildFromTemplate(template))
})

Menu.buildFromTemplate takes an array of items and returns a Menu; Menu.setApplicationMenu installs it. On Windows and Linux the menu appears at the top of each window; on macOS it appears in the system menu bar and is shared by all windows.

Property Purpose
label The visible text. Use & before a letter on Windows for a mnemonic
click(menuItem, browserWindow, event) Called on activation
role A built-in behavior and default label (copy, paste, undo, reload, quit, togglefullscreen...)
accelerator Keyboard shortcut, like CmdOrCtrl+Shift+S
type normal, separator, submenu, checkbox, radio
checked State for checkbox and radio items
enabled, visible Disable or hide an item
submenu Nested items
id Lets you find the item later with menu.getMenuItemById('id')

Roles are important: { role: 'copy' } gives you a correctly localized label, the right shortcut, and the right behavior on every platform. Never hand-roll Copy and Paste with click handlers when a role exists. Without an Edit menu, Ctrl+C and Ctrl+V can stop working in text fields on macOS.

Accelerators

An accelerator is a string of modifiers and one key joined with +:

  • Modifiers: Command (Cmd), Control (Ctrl), CommandOrControl (CmdOrCtrl), Alt, Option, Shift, Super.
  • Keys: letters and digits, F1 to F24, Plus, Space, Tab, Backspace, Delete, Enter, arrows (Up), Home, End, PageUp, PageDown, and more.

CmdOrCtrl is the standard choice so one definition works everywhere. Avoid clashes with system shortcuts (such as Alt+F4 on Windows or Cmd+Space on macOS).

Checkbox and radio items

JavaScript
{
  label: 'View',
  submenu: [
    { label: 'Word wrap', type: 'checkbox', checked: true,
      click: (item) => mainWindow.webContents.send('view:wrap', item.checked) },
    { type: 'separator' },
    { label: 'Light', type: 'radio', checked: true, click: () => setTheme('light') },
    { label: 'Dark', type: 'radio', click: () => setTheme('dark') },
  ],
}

Checkbox state toggles automatically when clicked, and item.checked holds the new value inside click. Radio items in the same group (adjacent radio items without other items between them) behave as a set.

Because a menu template is just an array of objects, you can generate and test it like any data. This stand-in flattens a template, resolves CmdOrCtrl per platform, and reports duplicate accelerators, a bug that makes shortcuts silently stop working.

Node.js Stand-in: inspect a menu template

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.

macOS differences

On macOS the first menu is the app menu named after your app (About, Preferences, Services, Hide, Quit). Use { role: 'appMenu' }. Put "Preferences" or "Settings" there (CmdOrCtrl+,) on macOS and in File or Edit on Windows and Linux. Also remember macOS has a "Window" menu convention, available through { role: 'windowMenu' }. Many apps build the template with isMac ? [...] : [...] spreads exactly as the first example.

Updating menus at runtime

You can change an item after the menu is built, for example to enable "Save" only when there is something to save:

JavaScript
const menu = Menu.getApplicationMenu()
menu.getMenuItemById('save').enabled = hasUnsavedChanges

Changing enabled, visible and checked works live. For structural changes (adding items), rebuild the template and call Menu.setApplicationMenu again.

Removing the menu bar

On Windows and Linux, win.setMenu(null) removes a window's menu, and win.setMenuBarVisibility(false) hides it until the user presses Alt. For apps with a completely custom UI you can set Menu.setApplicationMenu(null), but keep an Edit menu on macOS so copy and paste keep working.

Global shortcuts

Accelerators in menus work only when your app is focused. Global shortcuts work system-wide, even when your app is in the background, which suits recorders, launchers and clipboard tools. Use globalShortcut after ready:

JavaScript
const { globalShortcut, app } = require('electron')

app.whenReady().then(() => {
  const ok = globalShortcut.register('CommandOrControl+Shift+Space', () => {
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
  })
  if (!ok) console.warn('Shortcut is already used by another app')
})

app.on('will-quit', () => globalShortcut.unregisterAll())

register returns false if another application already owns the combination. Always unregister on quit and use global shortcuts sparingly: they steal keys from every other program. If you only need shortcuts while your window is focused, prefer a menu accelerator or the before-input-event of webContents:

JavaScript
win.webContents.on('before-input-event', (event, input) => {
  if (input.control && input.key.toLowerCase() === 'k') {
    event.preventDefault()
    win.webContents.send('command-palette')
  }
})

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why prefer role: 'copy' over a custom click handler for Copy?

    Roles provide localized labels, standard accelerators and the platform's real editing behavior, including in text fields.
  2. 2. What does the CmdOrCtrl modifier mean?

    CmdOrCtrl resolves to Command on macOS and Control on Windows and Linux, so one definition fits all.
  3. 3. Which API registers a shortcut that works when your app is not focused?

    globalShortcut hooks into the OS and works system-wide; menu accelerators only work while the app is focused.
  4. 4. When should you call globalShortcut.unregisterAll()?

    Release global shortcuts when quitting so they do not remain registered.

Summary

  • Menus are described as templates and built with Menu.buildFromTemplate, installed with setApplicationMenu.
  • Use roles for standard commands, CmdOrCtrl for accelerators, and watch for duplicate accelerators.
  • Handle macOS conventions (app menu, window menu) with an isMac check.
  • Update enabled, visible and checked live through getMenuItemById.
  • Use globalShortcut rarely, and unregister on will-quit.

Next: Context Menus and Native Dialogs