In Electron, menus are primarily categorized into the following types:
-
Application Menu: The Application Menu is the main menu positioned at the top of the application window, typically featuring common items such as File, Edit, View, Window, and Help. For example, on macOS, the Application Menu includes the application name menu, which commonly contains options like About, Services, Hide, and Quit.
-
Context Menu: The Context Menu appears upon right-clicking and is typically associated with specific contexts or interface elements. For instance, right-clicking within a text editing area may display options such as Cut, Copy, and Paste. This menu dynamically provides different options based on the current state or element type within the application.
-
Tray Menu: The Tray Menu is displayed when right-clicking or clicking on the system tray icon (or system notification area icon). It is commonly used for background-running applications, enabling users to quickly access features such as opening the main window or quitting the application.
Through Electron's Menu module, developers can flexibly construct and modify these menus. For example, you can use the following code snippet to create a simple Application Menu:
javascriptconst { Menu, MenuItem } = require('electron') const template = [ { label: 'Edit', submenu: [ { label: 'Undo', role: 'undo' }, { label: 'Redo', role: 'redo' }, { type: 'separator' }, { label: 'Cut', role: 'cut' }, { label: 'Copy', role: 'copy' }, { label: 'Paste', role: 'paste' } ] }, { label: 'View', submenu: [ { label: 'Reload', role: 'reload' }, { label: 'Toggle Fullscreen', role: 'togglefullscreen' } ] } ] const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu)
This code defines an Application Menu with two main items—"Edit" and "View"—each containing specific operation options. By utilizing the role attribute, Electron provides common behaviors such as Undo, Cut, Copy, and Paste, streamlining the development process.