Skip to main content

菜单

¥Menus

Electron 的 Menu 类提供了一种标准化的方法,可在整个应用中创建跨平台原生菜单。

¥Electron's Menu class provides a standardized way to create cross-platform native menus throughout your application.

Electron 中可用的菜单

¥Available menus in Electron

相同的菜单 API 可用于多种用例:

¥The same menu API is used for multiple use cases:

  • 应用菜单是你应用的顶层菜单。每个应用一次只有一个应用菜单。

    ¥The application menu is the top-level menu for your application. Each app only has a single application menu at a time.

  • 上下文菜单由用户右键单击应用界面的某个部分时触发。

    ¥Context menus are triggered by the user when right-clicking on a portion of your app's interface.

  • 托盘菜单是一个特殊的上下文菜单,在右键单击应用的 Tray 实例时触发。

    ¥The tray menu is a special context menu triggered when right-clicking on your app's Tray instance.

  • 在 macOS 上,Dock 菜单是一个特殊的上下文菜单,在系统 Dock 区域中右键单击应用图标时会触发。

    ¥On macOS, the dock menu is a special context menu triggered when right-clicking on your app's icon in the system Dock.

要了解更多关于你可以创建的各种原生菜单以及如何指定键盘快捷键的信息,请参阅本节中的各个指南:

¥To learn more about the various kinds of native menus you can create and how to specify keyboard shortcuts, see the individual guides in this section:

构建菜单

¥Building menus

每个 Menu 实例由一个 MenuItem 对象数组组成,可通过 menu.items 实例属性访问。可以通过将 item.submenu 属性设置为另一个菜单来嵌套菜单。

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

构建菜单的方法有两种:可以通过直接调用 menu.append 或使用静态 Menu.buildFromTemplate 辅助函数来实现。

¥There are two ways to build a menu: either by directly calling menu.append or by using the static Menu.buildFromTemplate helper function.

辅助函数允许你将 MenuItem 构造函数选项集合(或实例化的 MenuItem 实例)传递到单个数组中,而不必将每个项目附加到单独的函数调用中,从而减少了样板代码。

¥The helper function reduces boilerplate by allowing you to pass a collection of MenuItem constructor options (or instantiated MenuItem instances) in a single array rather than having to append each item in a separate function call.

下面是一个最小应用菜单的示例:

¥Below is an example of a minimal application menu:

menu.js
const submenu = new Menu()
submenu.append(new MenuItem({ label: 'Hello' }))
submenu.append(new MenuItem({ type: 'separator' }))
submenu.append(new MenuItem({ label: 'Electron', type: 'checkbox', checked: true }))
const menu = new Menu()
menu.append(new MenuItem({ label: 'Menu', submenu }))
Menu.setApplicationMenu(menu)

[!IMPORTANT] 所有菜单项(separator 类型除外)都必须带有标签。标签可以使用 label 属性手动定义,也可以从项目的 role 继承。

¥[!IMPORTANT] All menu items (except for the separator type) must have a label. Labels can either be manually defined using the label property or inherited from the item's role.

类型

¥Types

菜单项的类型赋予其特定的外观和功能。某些类型会根据其他构造函数选项自动分配:

¥A menu item's type grants it a particular appearance and functionality. Some types are automatically assigned based on other constructor options:

  • 默认情况下,菜单项的类型为 normal

    ¥By default, menu items have the normal type.

  • 包含 submenu 属性的菜单项将被分配 submenu 类型。

    ¥Menu items that contain the submenu property will be assigned the submenu type.

其他可用类型(指定后)会为菜单项赋予特殊的附加属性:

¥Other available types, when specified, give special additional properties to the menu item:

  • checkbox - 每当点击菜单项时切换 checked 属性

    ¥checkbox - toggles the checked property whenever the menu item is clicked

  • radio - 切换 checked 属性并关闭所有相邻 radio 项目的该属性

    ¥radio - toggles the checked property and turns off that property for all adjacent radio items

  • palette - 创建一个 Palette 子菜单,水平对齐菜单项(macOS 14 及更高版本可用)

    ¥palette - creates a Palette submenu, which aligns items horizontally (available on macOS 14 and above)

  • header - 创建一个部分标题,可以使用标签进行分组(macOS 14 及更高版本可用)

    ¥header - creates a section header, which can convey groupings with labels (available on macOS 14 and above)

[!TIP] 相邻的 radio 项位于同一级子菜单,且不被分隔符分隔。

¥[!TIP] Adjacent radio items are at the same level of submenu and not divided by a separator.

[
{ type: 'radio', label: 'Adjacent 1' },
{ type: 'radio', label: 'Adjacent 2' },
{ type: 'separator' },
{ type: 'radio', label: 'Non-adjacent' } // unaffected by the others
]

角色

¥Roles

角色为 normal 类型的菜单项赋予预定义的行为。

¥Roles give normal type menu items predefined behaviors.

我们建议为任何符合标准角色的菜单项指定 role 属性,而不是尝试在 click 函数中手动实现该行为。内置的 role 行为将提供最佳的原生体验。

¥We recommend specifying the role attribute for any menu item that matches a standard role rather than trying to manually implement the behavior in a click function. The built-in role behavior will give the best native experience.

使用 role 时,labelaccelerator 值是可选的,并且将默认为每个平台的适当值。

¥The label and accelerator values are optional when using a role and will default to appropriate values for each platform.

[!TIP] 角色字符串不区分大小写。例如,在定义菜单项时,toggleDevToolstoggledevtoolsTOGGLEDEVTOOLS 都是等效的角色。

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

编辑角色

¥Edit roles

  • undo

  • redo

  • cut

  • copy

  • paste

  • pasteAndMatchStyle

  • selectAll

  • delete

窗口角色

¥Window roles

  • about - 触发原生关于面板(Window 上的自定义消息框,它不提供自己的消息框)。

    ¥about - Trigger a native about panel (custom message box on Window, which does not provide its own).

  • minimize - 最小化当前窗口。

    ¥minimize - Minimize current window.

  • close - 关闭当前窗口。

    ¥close - Close current window.

  • quit - 退出应用。

    ¥quit - Quit the application.

  • reload - 重新加载当前窗口。

    ¥reload - Reload the current window.

  • forceReload - 重新加载当前窗口,忽略缓存。

    ¥forceReload - Reload the current window ignoring the cache.

  • toggleDevTools - 在当前窗口中切换开发者工具。

    ¥toggleDevTools - Toggle developer tools in the current window.

  • togglefullscreen - 在当前窗口上切换全屏模式。

    ¥togglefullscreen - Toggle full screen mode on the current window.

  • resetZoom - 将焦点页面的缩放级别重置为原始大小。

    ¥resetZoom - Reset the focused page's zoom level to the original size.

  • zoomIn - 将焦点页面放大 10%。

    ¥zoomIn - Zoom in the focused page by 10%.

  • zoomOut - 将焦点页面缩小 10%。

    ¥zoomOut - Zoom out the focused page by 10%.

  • toggleSpellChecker - 启用/禁用内置拼写检查器。

    ¥toggleSpellChecker - Enable/disable built-in spellchecker.

默认菜单角色

¥Default menu roles

  • fileMenu - 子菜单为 "文件" 菜单(关闭/退出)

    ¥fileMenu - The submenu is a "File" menu (Close / Quit)

  • editMenu - 子菜单为 "编辑" 菜单(撤消、复制等)

    ¥editMenu - The submenu is an "Edit" menu (Undo, Copy, etc.)

  • viewMenu - 子菜单为 "View" 菜单(重新加载、切换开发者工具等)

    ¥viewMenu - The submenu is a "View" menu (Reload, Toggle Developer Tools, etc.)

  • windowMenu - 子菜单为 "窗户" 菜单(最小化、缩放等)

    ¥windowMenu - The submenu is a "Window" menu (Minimize, Zoom, etc.)

macOS 独有角色

¥macOS-only roles

macOS 有许多特定于平台的菜单角色可用。其中许多映射到底层 AppKit API。

¥macOS has a number of platform-specific menu roles available. Many of these map to underlying AppKit APIs.

应用管理角色

¥App management roles

编辑角色

¥Edit roles

语音角色

¥Speech roles

原生标签角色

¥Native tab roles

默认菜单角色

¥Default menu roles

  • appMenu - 整个默认 "应用" 菜单(关于、服务等)

    ¥appMenu - Whole default "App" menu (About, Services, etc.)

  • services - 子菜单是 "服务" 菜单。

    ¥services - The submenu is a "Services" menu.

  • window - 子菜单是 "窗户" 菜单。

    ¥window - The submenu is a "Window" menu.

  • help - 子菜单是 "帮助" 菜单。

    ¥help - The submenu is a "Help" menu.

其他菜单角色

¥Other menu roles

  • recentDocuments - 子菜单是 "最近打开" 菜单。

    ¥recentDocuments - The submenu is an "Open Recent" menu.

  • clearRecentDocuments - 映射到 clearRecentDocuments 操作。

    ¥clearRecentDocuments - Map to the clearRecentDocuments action.

  • shareMenu - 子菜单为 [共享菜单][ShareMenu]。还必须设置 sharingItem 属性以指示要共享的项目。

    ¥shareMenu - The submenu is [share menu][ShareMenu]. The sharingItem property must also be set to indicate the item to share.

[!IMPORTANT] 在 macOS 上指定 role 时,只有 labelaccelerator 选项会影响菜单项。所有其他选项将被忽略。

¥[!IMPORTANT] When specifying a role on macOS, label and accelerator are the only options that will affect the menu item. All other options will be ignored.

加速器

¥Accelerators

accelerator 属性允许你定义加速器字符串,以将菜单项映射到键盘快捷键。更多详情,请参阅 键盘快捷键 指南。

¥The accelerator property allows you to define accelerator strings to map menu items to keyboard shortcuts. For more details, see the Keyboard Shortcuts guide.

高级配置

¥Advanced configuration

程序化项目定位

¥Programmatic item positioning

使用 Menu.buildFromTemplate 构建菜单时,你可以使用 beforeafterbeforeGroupContainingafterGroupContainingid 属性来控制菜单项的放置方式。

¥You can make use of the before, after, beforeGroupContaining, afterGroupContaining and id attributes to control how menu items will be placed when building a menu with Menu.buildFromTemplate.

  • before - 将此项目插入到具有指定 id 的项目之前。如果引用的项目不存在,该项目将插入到菜单的末尾。还意味着相关菜单项应放置在与该项目相同的“组”中。

    ¥before - Inserts this item before the item with the specified id. If the referenced item doesn't exist, the item will be inserted at the end of the menu. Also implies that the menu item in question should be placed in the same “group” as the item.

  • after - 将此项目插入到具有指定 id 的项目之后。如果引用的项目不存在,该项目将插入到菜单的末尾。还意味着相关菜单项应放置在与该项目相同的“组”中。

    ¥after - Inserts this item after the item with the specified id. If the referenced item doesn't exist, the item will be inserted at the end of the menu. Also implies that the menu item in question should be placed in the same “group” as the item.

  • beforeGroupContaining - 为单个上下文菜单提供一种方法,以声明其包含组位于具有指定 id 的项目的包含组之前。

    ¥beforeGroupContaining - Provides a means for a single context menu to declare the placement of their containing group before the containing group of the item with the specified id.

  • afterGroupContaining - 为单个上下文菜单提供一种方法,以声明其包含组在具有指定 id 的项目的包含组之后的位置。

    ¥afterGroupContaining - Provides a means for a single context menu to declare the placement of their containing group after the containing group of the item with the specified id.

默认情况下,除非使用指定的定位关键字之一,否则项目将按照它们在模板中存在的顺序插入。

¥By default, items will be inserted in the order they exist in the template unless one of the specified positioning keywords is used.

示例

¥Examples

模板:

¥Template:

[
{ id: '1', label: 'one' },
{ id: '2', label: 'two' },
{ id: '3', label: 'three' },
{ id: '4', label: 'four' }
]

菜单:

¥Menu:

- one
- two
- three
- four

模板:

¥Template:

[
{ id: '1', label: 'one' },
{ type: 'separator' },
{ id: '3', label: 'three', beforeGroupContaining: ['1'] },
{ id: '4', label: 'four', afterGroupContaining: ['2'] },
{ type: 'separator' },
{ id: '2', label: 'two' }
]

菜单:

¥Menu:

- three
- four
- ---
- one
- ---
- two

模板:

¥Template:

[
{ id: '1', label: 'one', after: ['3'] },
{ id: '2', label: 'two', before: ['1'] },
{ id: '3', label: 'three' }
]

菜单:

¥Menu:

- ---
- three
- two
- one

图标

¥Icons

要为菜​​单添加视觉辅助,你可以使用 icon 属性将图片分配给各个 MenuItem 实例。

¥To add visual aid to your menus, you can use the icon property to assign images to individual MenuItem instances.

Adding a little green circle to a menu item
const { nativeImage } = require('electron/common')
const { MenuItem } = require('electron/main')

const green = nativeImage.createFromDataURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAACOSURBVHgBpZLRDYAgEEOrEzgCozCCGzkCbKArOIlugJvgoRAUNcLRpvGH19TkgFQWkqIohhK8UEaKwKcsOg/+WR1vX+AlA74u6q4FqgCOSzwsGHCwbKliAF89Cv89tWmOT4VaVMoVbOBrdQUz+FrD6XItzh4LzYB1HFJ9yrEkZ4l+wvcid9pTssh4UKbPd+4vED2Nd54iAAAAAElFTkSuQmCC')

const item = new MenuItem({
label: 'Green Circle',
icon: green
})

子标签 macOS

¥Sublabels macOS

你可以使用 macOS 14.4 及更高版本上的 sublabel 选项向菜单项添加子标签(也称为 subtitles)。

¥You can add sublabels (also known as subtitles) to menu items using the sublabel option on macOS 14.4 and above.

Adding descriptions via sublabel
const { MenuItem } = require('electron/main')

const item = new MenuItem({
label: 'Log Message',
sublabel: 'This will use the console.log utility',
click: () => { console.log('Logging via menu...') }
})

工具提示 macOS

¥Tooltips macOS

工具提示是当你将鼠标悬停在菜单项上时出现的信息指示。在 macOS 上,你可以使用 toolTip 选项设置菜单项的工具提示。

¥Tooltips are informational indicators that appear when you hover over a menu item. You can set menu item tooltips on macOS using the toolTip option.

Adding additional information via tooltip
const { MenuItem } = require('electron/main')

const item = new MenuItem({
label: 'Hover Over Me',
toolTip: 'This is additional info that appears on hover'
})