new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Electron · Tutorial · all subjects

application-menu

50 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Default menu structure when API not called

Electron will set a default menu for your app if the Menu.setApplicationMenu API is never called.

macOS first submenu label requirement

On macOS, the first submenu of the application menu will always have your application's name as its label.

Top-level menu items must be submenus

When building an application menu in Electron, each top-level array menu item must be a submenu.

Application menu location on different platforms

Each Electron app has a single top-level application menu. On macOS, this menu is shown in the system menu bar. On Windows and Linux, this menu is shown at the top of each BaseWindow.

Setting the application menu

The application menu is set by passing a Menu instance into the Menu.setApplicationMenu static function.

Using MenuItem roles in application menu

Electron provides submenu-related roles that can be used to reduce verbosity when building application menus. Standard roles include appMenu, fileMenu, editMenu, viewMenu, windowMenu, and help.

Help role on macOS with search bar

On macOS, the help role defines a top-level Help submenu that has a search bar for other menu items. It requires items to be added to its submenu to function.

Window-specific menus on Windows and Linux

Since the root application menu exists on each BaseWindow on Windows and Linux, you can override it with a window-specific Menu instance via the win.setMenu method.

Removing a window-specific menu

A specific window's application menu can be removed by calling the win.removeMenu API, available on Windows and Linux.

Building application menu from template

Application menus can be built from a template using the Menu.buildFromTemplate method, which accepts an array of menu item objects.

Manually creating the default menu example

This example shows how to manually create a default Electron application menu using MenuItem roles, with conditional logic for macOS vs Windows/Linux differences. ```js const { shell } = require('electron/common') const { app, Menu } = require('electron/main') const isMac = process.platform === 'darwin' const template = [ // { role: 'appMenu' } ...(isMac ? [{ label: app.name, submenu: [ { role: 'about' }, { type: 'separator' }, { role: 'services' }, { type: 'separator' }, { role: 'hide' }, { role: 'hideOthers' }, { role: 'unhide' }, { type: 'separator' }, { role: 'quit' } ] }] : []), // { role: 'fileMenu' } { label: 'File', submenu: [ isMac ? { role: 'close' } : { role: 'quit' } ] }, // { role: 'editMenu' } { label: 'Edit', submenu: [ { role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, ...(isMac ? [ { role: 'pasteAndMatchStyle' }, { role: 'delete' }, { role: 'selectAll' }, { type: 'separator' }, { label: 'Speech', submenu: [ { role: 'startSpeaking' }, { role: 'stopSpeaking' } ] } ] : [ { role: 'delete' }, { type: 'separator' }, { role: 'selectAll' } ]) ] }, // { role: 'viewMenu' } { label: 'View', submenu: [ { role: 'reload' }, { role: 'forceReload' }, { role: 'toggleDevTools' }, { type: 'separator' }, { role: 'resetZoom' }, { role: 'zoomIn' }, { role: 'zoomOut' }, { type: 'separator' }, { role: 'togglefullscreen' } ] }, // { role: 'windowMenu' } { label: 'Window', submenu: [ { role: 'minimize' }, { role: 'zoom' }, ...(isMac ? [ { type: 'separator' }, { role: 'front' }, { type: 'separator' }, { role: 'window' } ] : [ { role: 'close' } ]) ] }, { role: 'help', submenu: [ { label: 'Learn More', click: async () => { const { shell } = require('electron') await shell.openExternal('https://electronjs.org') } } ] } ] const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ```

Using default roles for application menu example

This example shows how to create an application menu using default roles for each submenu, reducing verbosity compared to manually defining each menu item. ```js const { shell } = require('electron/common') const { app, Menu } = require('electron/main') const template = [ ...(process.platform === 'darwin' ? [{ role: 'appMenu' }] : []), { role: 'fileMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' }, { role: 'help', submenu: [ { label: 'Learn More', click: async () => { const { shell } = require('electron') await shell.openExternal('https://electronjs.org') } } ] } ] const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) ```

Override a window's menu example

This example shows how to set a window-specific menu that overrides the application menu on Windows and Linux using the win.setMenu method. ```js const { BrowserWindow, Menu } = require('electron/main') const win = new BrowserWindow() const menu = Menu.buildFromTemplate([ { label: 'my custom menu', submenu: [ { role: 'copy' }, { role: 'paste' } ] } ]) win.setMenu(menu) ```

Context menus do not appear by default in Electron

No context menu will appear by default in Electron. Context menus must be explicitly created by using the menu.popup function on an instance of the Menu class.

Two ways to listen for context menu events in Electron

Context menu events can be listened for in two ways: via the main process through webContents, or in the renderer process via the contextmenu web event.

context-menu event triggered in main process

Whenever a right-click is detected within the bounds of a specific WebContents instance, a context-menu event is triggered in the main process. The params object passed to the listener provides attributes to distinguish which type of element is receiving the event, such as linkURL for links and isEditable for editable elements.

contextmenu event in renderer process calls menu.popup via IPC

You can listen to the contextmenu event available on DOM elements in the renderer process and call the menu.popup function via IPC to trigger a context menu.

macOS context menu items disabled by default

On macOS, Writing Tools, AutoFill, and Services menu items are disabled by default for context menus in Electron.

Enable macOS context menu features with frame parameter

To enable Writing Tools, AutoFill, and Services features on macOS, pass the WebFrameMain associated to the target webContents to the frame parameter in menu.popup.

Example: context menu with frame parameter for macOS features

const { BrowserWindow, Menu } = require('electron/main') const menu = Menu.buildFromTemplate([{ role: 'editMenu' }]) const win = new BrowserWindow() win.webContents.on('context-menu', (_event, params) => { if (params.isEditable) { menu.popup({ frame: params.frame }) } })

Desktop actions defined in .desktop file on Linux

On Linux environments, custom entries can be added to the system launcher by modifying the `.desktop` file. To create a shortcut action, provide `Name` and `Exec` properties for each entry. The desktop executes the command defined in the `Exec` field when the user clicks the shortcut menu item. Actions are declared in an `Actions` property listing the action identifiers separated by semicolons, then each action is defined in its own section like `[Desktop Action ActionName]`.

Linux desktop launcher action example

Example `.desktop` file with three custom actions for an audio player: ```plaintext Actions=PlayPause;Next;Previous [Desktop Action PlayPause] Name=Play-Pause Exec=audacious -t [Desktop Action Next] Name=Next Exec=audacious -f [Desktop Action Previous] Name=Previous Exec=audacious -r ```

Linux desktop launcher action parameters via process.argv

The preferred way for the desktop to instruct an application what action to perform is through command-line parameters. These parameters can be accessed in the application via the global variable `process.argv`.

Menu types available in Electron

Electron provides four types of menus: application menu (top-level menu, one per app), context menus (triggered by right-clicking), tray menu (right-click on Tray instance), and dock menu on macOS (right-click on app icon in system Dock).

Menu composition with MenuItem objects

Each Menu instance is composed of an array of MenuItem objects accessible via the menu.items property. Menus can be nested by setting the item.submenu property to another menu.

Two methods to build menus

Menus can be built in two ways: directly calling menu.append() with MenuItem objects, or using the static Menu.buildFromTemplate() helper function which accepts an array of MenuItem constructor options in a single call.

Menu item label requirement

All menu items except those with type 'separator' must have a label. Labels can be manually defined using the label property or inherited from the item's role.

MenuItem type property behavior

Menu item types determine appearance and functionality. By default, items have type 'normal'. Items with a submenu property are automatically assigned type 'submenu'. Other available types when specified are: checkbox (toggles checked property on click), radio (toggles checked and turns off for adjacent radio items), palette (creates horizontally-aligned submenu on macOS 14+), and header (creates section header on macOS 14+).

Adjacent radio items behavior

Adjacent radio items at the same submenu level (not divided by a separator) will have their checked property toggled together. Radio items separated by a separator are not adjacent and do not affect each other.

Roles provide predefined menu behaviors

Roles give normal type menu items predefined behaviors corresponding to standard application actions. Using roles is recommended over manually implementing behavior in click functions, as built-in role behavior provides the best native experience. Label and accelerator values are optional when using a role and default to appropriate values for each platform.

Role strings are case-insensitive

Role strings are case-insensitive. For example, toggleDevTools, toggledevtools, and TOGGLEDEVTOOLS are all equivalent roles when defining menu items.

Edit roles for menu items

Available edit roles are: undo, redo, cut, copy, paste, pasteAndMatchStyle, selectAll, delete.

Window roles for menu items

Available window roles are: about (trigger native about panel), minimize, close, quit, reload, forceReload, toggleDevTools, togglefullscreen, resetZoom, zoomIn, zoomOut, toggleSpellChecker.

Default menu roles for submenus

Default menu roles that create standard submenus are: fileMenu (File menu with Close/Quit), editMenu (Edit menu with Undo, Copy, etc.), viewMenu (View menu with Reload, Toggle Developer Tools, etc.), windowMenu (Window menu with Minimize, Zoom, etc.).

macOS app management roles

macOS-specific app management roles are: hide (maps to AppKit hide action), hideOthers (maps to hideOtherApplications), unhide (maps to unhideAllApplications), front (maps to arrangeInFront), zoom (maps to performZoom).

macOS edit roles for text

macOS-specific edit roles for text are: showSubstitutions (maps to orderFrontSubstitutionsPanel), toggleSmartQuotes (maps to toggleAutomaticQuoteSubstitution), toggleSmartDashes (maps to toggleAutomaticDashSubstitution), toggleTextReplacement (maps to toggleAutomaticTextReplacement).

macOS speech roles

macOS-specific speech roles are: startSpeaking (maps to AppKit startSpeaking action), stopSpeaking (maps to stopSpeaking action).

macOS native tab roles

macOS-specific native tab roles are: toggleTabBar, selectNextTab, selectPreviousTab, mergeAllWindows, moveTabToNewWindow.

macOS default menu roles

macOS-specific default menu roles are: appMenu (entire default App menu with About, Services, etc.), services (Services submenu), window (Window submenu), help (Help submenu).

macOS other menu roles

macOS-specific other menu roles are: recentDocuments (Open Recent submenu), clearRecentDocuments (maps to clearRecentDocuments action), shareMenu (share menu submenu, requires sharingItem property to specify item to share).

macOS role ignores other options

When specifying a role on macOS, only label and accelerator options will affect the menu item. All other options will be ignored.

Programmatic menu item positioning with before/after

Use the before and after attributes to control menu item placement in Menu.buildFromTemplate. The before attribute inserts an item before the item with the specified id (or at the end if not found) and places the item in the same group. The after attribute inserts an item after the item with the specified id (or at the end if not found) and places the item in the same group.

Programmatic menu item positioning with beforeGroupContaining/afterGroupContaining

Use the beforeGroupContaining and afterGroupContaining attributes to control menu item group placement in Menu.buildFromTemplate. beforeGroupContaining places the containing group before the containing group of the item with the specified id. afterGroupContaining places the containing group after the containing group of the item with the specified id.

Menu item positioning with id attribute

Use the id attribute to identify menu items for positioning purposes with before, after, beforeGroupContaining, and afterGroupContaining. By default, items are inserted in the order they exist in the template unless positioning keywords are used.

Adding icons to menu items

Use the icon property on MenuItem to assign images to menu items. Icons can be created using nativeImage.createFromDataURL() or other nativeImage methods.

Menu item sublabel on macOS 14.4+

Sublabels (also known as subtitles) can be added to menu items on macOS 14.4 and above using the sublabel option on MenuItem.

Menu item tooltips on macOS

Tooltips can be added to menu items on macOS using the toolTip option on MenuItem. Tooltips are informational indicators that appear when hovering over a menu item.

Accelerator property maps keyboard shortcuts

The accelerator property allows defining accelerator strings to map menu items to keyboard shortcuts. See the Keyboard Shortcuts guide for more details on accelerator strings.

Attach context menu to Tray with setContextMenu

Pass a Menu instance into the tray.setContextMenu() function to attach a context menu to a Tray object. Unlike regular context menus, Tray context menus do not need to be manually instrumented using the menu.popup API; the Tray object handles click events automatically.

enabled and visibility properties unsupported for top-level tray menu items on macOS

The 'enabled' and 'visibility' properties are not available for top-level menu items in the tray context menu on macOS.

Give your agent this brain