patterntypescriptTip
Electron native application menus
Viewed 0 times
MenuMenuItemapplication menuroleacceleratorkeyboard shortcut
electron
Problem
Electron apps need a native OS menu bar (File, Edit, View, etc.) with keyboard shortcuts and dynamic items that reflect app state.
Solution
Build a Menu template array and call Menu.setApplicationMenu(). Rebuild and reset the menu when app state changes. Use roles for standard OS behaviors (cut, copy, quit).
Why
Using built-in roles ensures OS-native behavior and keyboard shortcuts without manually implementing them. Custom items use click handlers that dispatch to main process logic.
Gotchas
- Menu.setApplicationMenu(null) removes the menu entirely — useful for kiosk apps
- On macOS, the first menu item is always the app name menu; the label is overridden by the OS
- Dynamic menus should be rebuilt completely — there is no patch API
- Accelerators use different modifier strings: 'CmdOrCtrl', 'Alt', 'Shift'
Code Snippets
Building a simple menu
const template: MenuItemConstructorOptions[] = [
{
label: 'File',
submenu: [
{ label: 'Open', accelerator: 'CmdOrCtrl+O', click: () => openFile() },
{ type: 'separator' },
{ role: 'quit' },
],
},
{ role: 'editMenu' },
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));Revisions (0)
No revisions yet.