docs: add Menu module tutorials (#47268)

* docs: add `Menu` module tutorials

* link API docs to new tutorials

* removed unreferenced fiddles

* add wording for new types

* fix import sort errors

* delete accelerator.md

* fixes
This commit is contained in:
Erick Zhao 2025-07-15 15:09:32 -07:00 committed by GitHub
commit cc9ca4bee2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
39 changed files with 1240 additions and 1472 deletions

View file

@ -1,82 +0,0 @@
# Accelerator
> Define keyboard shortcuts.
Accelerators are strings that can contain multiple modifiers and a single key code,
combined by the `+` character, and are used to define keyboard shortcuts
throughout your application. Accelerators are case insensitive.
Examples:
* `CommandOrControl+A`
* `CommandOrControl+Shift+Z`
Shortcuts are registered with the [`globalShortcut`](global-shortcut.md) module
using the [`register`](global-shortcut.md#globalshortcutregisteraccelerator-callback)
method, i.e.
```js
const { app, globalShortcut } = require('electron')
app.whenReady().then(() => {
// Register a 'CommandOrControl+Y' shortcut listener.
globalShortcut.register('CommandOrControl+Y', () => {
// Do stuff when Y and either Command/Control is pressed.
})
})
```
## Platform notice
On Linux and Windows, the `Command` key does not have any effect so
use `CommandOrControl` which represents `Command` on macOS and `Control` on
Linux and Windows to define some accelerators.
Use `Alt` instead of `Option`. The `Option` key only exists on macOS, whereas
the `Alt` key is available on all platforms.
The `Super` (or `Meta`) key is mapped to the `Windows` key on Windows and Linux and
`Cmd` on macOS.
## Available modifiers
* `Command` (or `Cmd` for short)
* `Control` (or `Ctrl` for short)
* `CommandOrControl` (or `CmdOrCtrl` for short)
* `Alt`
* `Option`
* `AltGr`
* `Shift`
* `Super`
* `Meta`
## Available key codes
* `0` to `9`
* `A` to `Z`
* `F1` to `F24`
* Various Punctuation: `)`, `!`, `@`, `#`, `$`, `%`, `^`, `&`, `*`, `(`, `:`, `;`, `:`, `+`, `=`, `<`, `,`, `_`, `-`, `>`, `.`, `?`, `/`, `~`, `` ` ``, `{`, `]`, `[`, `|`, `\`, `}`, `"`
* `Plus`
* `Space`
* `Tab`
* `Capslock`
* `Numlock`
* `Scrolllock`
* `Backspace`
* `Delete`
* `Insert`
* `Return` (or `Enter` as alias)
* `Up`, `Down`, `Left` and `Right`
* `Home` and `End`
* `PageUp` and `PageDown`
* `Escape` (or `Esc` for short)
* `VolumeUp`, `VolumeDown` and `VolumeMute`
* `MediaNextTrack`, `MediaPreviousTrack`, `MediaStop` and `MediaPlayPause`
* `PrintScreen`
* NumPad Keys
* `num0` - `num9`
* `numdec` - decimal key
* `numadd` - numpad `+` key
* `numsub` - numpad `-` key
* `nummult` - numpad `*` key
* `numdiv` - numpad `÷` key

View file

@ -5,13 +5,8 @@
Process: [Main](../glossary.md#main-process)<br />
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
The following example shows how to bounce your icon on the dock.
```js
const { app } = require('electron')
app.dock?.bounce()
```
> [!TIP]
> See also: [A detailed guide about how to implement Dock menus](../tutorial/macos-dock.md).
### Instance Methods
@ -50,6 +45,9 @@ Bounces the Downloads stack if the filePath is inside the Downloads folder.
Sets the string to be displayed in the docks badging area.
> [!IMPORTANT]
> You need to ensure that your application has the permission to display notifications for this method to work.
#### `dock.getBadge()` _macOS_
Returns `string` - The badge string of the dock.

View file

@ -46,13 +46,16 @@ app.on('will-quit', () => {
})
```
> [!TIP]
> See also: [A detailed guide on Keyboard Shortcuts](../tutorial/keyboard-shortcuts.md).
## Methods
The `globalShortcut` module has the following methods:
### `globalShortcut.register(accelerator, callback)`
* `accelerator` [Accelerator](accelerator.md)
* `accelerator` string - An [accelerator](../tutorial/keyboard-shortcuts.md#accelerators) shortcut.
* `callback` Function
Returns `boolean` - Whether or not the shortcut was registered successfully.
@ -74,7 +77,7 @@ the app has been authorized as a [trusted accessibility client](https://develope
### `globalShortcut.registerAll(accelerators, callback)`
* `accelerators` [Accelerator](accelerator.md)[] - an array of [Accelerator](accelerator.md)s.
* `accelerators` string[] - An array of [accelerator](../tutorial/keyboard-shortcuts.md#accelerators) shortcuts.
* `callback` Function
Registers a global shortcut of all `accelerator` items in `accelerators`. The `callback` is called when any of the registered shortcuts are pressed by the user.
@ -93,7 +96,7 @@ the app has been authorized as a [trusted accessibility client](https://develope
### `globalShortcut.isRegistered(accelerator)`
* `accelerator` [Accelerator](accelerator.md)
* `accelerator` string - An [accelerator](../tutorial/keyboard-shortcuts.md#accelerators) shortcut.
Returns `boolean` - Whether this application has registered `accelerator`.
@ -103,7 +106,7 @@ don't want applications to fight for global shortcuts.
### `globalShortcut.unregister(accelerator)`
* `accelerator` [Accelerator](accelerator.md)
* `accelerator` string - An [accelerator](../tutorial/keyboard-shortcuts.md#accelerators) shortcut.
Unregisters the global shortcut of `accelerator`.

View file

@ -19,7 +19,7 @@ See [`Menu`](menu.md) for examples.
* `window` [BaseWindow](base-window.md) | undefined - This will not be defined if no window is open.
* `event` [KeyboardEvent](structures/keyboard-event.md)
* `role` string (optional) - Can be `undo`, `redo`, `cut`, `copy`, `paste`, `pasteAndMatchStyle`, `delete`, `selectAll`, `reload`, `forceReload`, `toggleDevTools`, `resetZoom`, `zoomIn`, `zoomOut`, `toggleSpellChecker`, `togglefullscreen`, `window`, `minimize`, `close`, `help`, `about`, `services`, `hide`, `hideOthers`, `unhide`, `quit`, `showSubstitutions`, `toggleSmartQuotes`, `toggleSmartDashes`, `toggleTextReplacement`, `startSpeaking`, `stopSpeaking`, `zoom`, `front`, `appMenu`, `fileMenu`, `editMenu`, `viewMenu`, `shareMenu`, `recentDocuments`, `toggleTabBar`, `selectNextTab`, `selectPreviousTab`, `showAllTabs`, `mergeAllWindows`, `clearRecentDocuments`, `moveTabToNewWindow` or `windowMenu` - Define the action of the menu item, when specified the
`click` property will be ignored. See [roles](#roles).
`click` property will be ignored. See [roles](../tutorial/menus.md#roles).
* `type` string (optional)
* `normal`
* `separator`
@ -31,7 +31,7 @@ See [`Menu`](menu.md) for examples.
* `label` string (optional)
* `sublabel` string (optional) _macOS_ - Available in macOS >= 14.4
* `toolTip` string (optional) _macOS_ - Hover text for this menu item.
* `accelerator` [Accelerator](accelerator.md) (optional)
* `accelerator` string (optional) - An [Accelerator](../tutorial/keyboard-shortcuts.md#accelerators) string.
* `icon` ([NativeImage](native-image.md) | string) (optional)
* `enabled` boolean (optional) - If false, the menu item will be greyed out and
unclickable.
@ -64,88 +64,13 @@ See [`Menu`](menu.md) for examples.
> [!NOTE]
> `acceleratorWorksWhenHidden` is specified as being macOS-only because accelerators always work when items are hidden on Windows and Linux. The option is exposed to users to give them the option to turn it off, as this is possible in native macOS development.
### Roles
Roles allow menu items to have predefined behaviors.
It is best to specify `role` 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.
The `label` and `accelerator` values are optional when using a `role` and will
default to appropriate values for each platform.
Every menu item must have either a `role`, `label`, or in the case of a separator
a `type`.
The `role` property can have following values:
* `undo`
* `about` - Trigger a native about panel (custom message box on Window, which does not provide its own).
* `redo`
* `cut`
* `copy`
* `paste`
* `pasteAndMatchStyle`
* `selectAll`
* `delete`
* `minimize` - Minimize current window.
* `close` - Close current window.
* `quit` - Quit the application.
* `reload` - Reload the current window.
* `forceReload` - Reload the current window ignoring the cache.
* `toggleDevTools` - Toggle developer tools in the current window.
* `togglefullscreen` - Toggle full screen mode on the current window.
* `resetZoom` - Reset the focused page's zoom level to the original size.
* `zoomIn` - Zoom in the focused page by 10%.
* `zoomOut` - Zoom out the focused page by 10%.
* `toggleSpellChecker` - Enable/disable builtin spell checker.
* `fileMenu` - Whole default "File" menu (Close / Quit)
* `editMenu` - Whole default "Edit" menu (Undo, Copy, etc.).
* `viewMenu` - Whole default "View" menu (Reload, Toggle Developer Tools, etc.)
* `windowMenu` - Whole default "Window" menu (Minimize, Zoom, etc.).
The following additional roles are available on _macOS_:
* `appMenu` - Whole default "App" menu (About, Services, etc.)
* `hide` - Map to the `hide` action.
* `hideOthers` - Map to the `hideOtherApplications` action.
* `unhide` - Map to the `unhideAllApplications` action.
* `showSubstitutions` - Map to the `orderFrontSubstitutionsPanel` action.
* `toggleSmartQuotes` - Map to the `toggleAutomaticQuoteSubstitution` action.
* `toggleSmartDashes` - Map to the `toggleAutomaticDashSubstitution` action.
* `toggleTextReplacement` - Map to the `toggleAutomaticTextReplacement` action.
* `startSpeaking` - Map to the `startSpeaking` action.
* `stopSpeaking` - Map to the `stopSpeaking` action.
* `front` - Map to the `arrangeInFront` action.
* `zoom` - Map to the `performZoom` action.
* `toggleTabBar` - Map to the `toggleTabBar` action.
* `selectNextTab` - Map to the `selectNextTab` action.
* `selectPreviousTab` - Map to the `selectPreviousTab` action.
* `showAllTabs` - Map to the `showAllTabs` action.
* `mergeAllWindows` - Map to the `mergeAllWindows` action.
* `moveTabToNewWindow` - Map to the `moveTabToNewWindow` action.
* `window` - The submenu is a "Window" menu.
* `help` - The submenu is a "Help" menu.
* `services` - The submenu is a ["Services"](https://developer.apple.com/documentation/appkit/nsapplication/1428608-servicesmenu?language=objc) menu. This is only intended for use in the Application Menu and is _not_ the same as the "Services" submenu used in context menus in macOS apps, which is not implemented in Electron.
* `recentDocuments` - The submenu is an "Open Recent" menu.
* `clearRecentDocuments` - Map to the `clearRecentDocuments` action.
* `shareMenu` - The submenu is [share menu][ShareMenu]. The `sharingItem` property must also be set to indicate the item to share.
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.
Lowercase `role`, e.g. `toggledevtools`, is still supported.
> [!NOTE]
> The `enabled` and `visibility` properties are not available for top-level menu items in the tray on macOS.
### Instance Properties
The following properties are available on instances of `MenuItem`:
#### `menuItem.id`
A `string` indicating the item's unique id, this property can be
A `string` indicating the item's unique id. This property can be
dynamically changed.
#### `menuItem.label`
@ -203,17 +128,17 @@ A `string` indicating the item's hover text.
#### `menuItem.enabled`
A `boolean` indicating whether the item is enabled, this property can be
A `boolean` indicating whether the item is enabled. This property can be
dynamically changed.
#### `menuItem.visible`
A `boolean` indicating whether the item is visible, this property can be
A `boolean` indicating whether the item is visible. This property can be
dynamically changed.
#### `menuItem.checked`
A `boolean` indicating whether the item is checked, this property can be
A `boolean` indicating whether the item is checked. This property can be
dynamically changed.
A `checkbox` menu item will toggle the `checked` property on and off when
@ -244,5 +169,3 @@ A `number` indicating an item's sequential unique id.
#### `menuItem.menu`
A `Menu` that the item is a part of.
[ShareMenu]: https://developer.apple.com/design/human-interface-guidelines/macos/extensions/share-extensions/

View file

@ -6,6 +6,9 @@
Process: [Main](../glossary.md#main-process)
> [!TIP]
> See also: [A detailed guide about how to implement menus in your application](../tutorial/menus.md).
> [!WARNING]
> Electron's built-in classes cannot be subclassed in user code.
> For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules).
@ -20,7 +23,7 @@ The `Menu` class has the following static methods:
#### `Menu.setApplicationMenu(menu)`
* `menu` Menu | null
- `menu` Menu | null
Sets `menu` as the application menu on macOS. On Windows and Linux, the
`menu` will be set as each window's top menu.
@ -51,18 +54,18 @@ Returns `Menu | null` - The application menu, if set, or `null`, if not set.
#### `Menu.sendActionToFirstResponder(action)` _macOS_
* `action` string
- `action` string
Sends the `action` to the first responder of application. This is used for
emulating default macOS menu behaviors. Usually you would use the
[`role`](menu-item.md#roles) property of a [`MenuItem`](menu-item.md).
[`role`](../tutorial/menus.md#roles) property of a [`MenuItem`](menu-item.md).
See the [macOS Cocoa Event Handling Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/EventOverview/EventArchitecture/EventArchitecture.html#//apple_ref/doc/uid/10000060i-CH3-SW7)
for more information on macOS' native actions.
#### `Menu.buildFromTemplate(template)`
* `template` (MenuItemConstructorOptions | MenuItem)[]
- `template` (MenuItemConstructorOptions | MenuItem)[]
Returns `Menu`
@ -77,47 +80,50 @@ The `menu` object has the following instance methods:
#### `menu.popup([options])`
* `options` Object (optional)
* `window` [BaseWindow](base-window.md) (optional) - Default is the focused window.
* `frame` [WebFrameMain](web-frame-main.md) (optional) - Provide the relevant frame
- `options` Object (optional)
- `window` [BaseWindow](base-window.md) (optional) - Default is the focused window.
- `frame` [WebFrameMain](web-frame-main.md) (optional) - Provide the relevant frame
if you want certain OS-level features such as Writing Tools on macOS to function correctly. Typically, this should be `params.frame` from the [`context-menu` event](web-contents.md#event-context-menu) on a WebContents, or the [`focusedFrame` property](web-contents.md#contentsfocusedframe-readonly) of a WebContents.
* `x` number (optional) - Default is the current mouse cursor position.
- `x` number (optional) - Default is the current mouse cursor position.
Must be declared if `y` is declared.
* `y` number (optional) - Default is the current mouse cursor position.
- `y` number (optional) - Default is the current mouse cursor position.
Must be declared if `x` is declared.
* `positioningItem` number (optional) _macOS_ - The index of the menu item to
- `positioningItem` number (optional) _macOS_ - The index of the menu item to
be positioned under the mouse cursor at the specified coordinates. Default
is -1.
* `sourceType` string (optional) _Windows_ _Linux_ - This should map to the `menuSourceType`
- `sourceType` string (optional) _Windows_ _Linux_ - This should map to the `menuSourceType`
provided by the `context-menu` event. It is not recommended to set this value manually,
only provide values you receive from other APIs or leave it `undefined`.
Can be `none`, `mouse`, `keyboard`, `touch`, `touchMenu`, `longPress`, `longTap`, `touchHandle`, `stylus`, `adjustSelection`, or `adjustSelectionReset`.
* `callback` Function (optional) - Called when menu is closed.
- `callback` Function (optional) - Called when menu is closed.
Pops up this menu as a context menu in the [`BaseWindow`](base-window.md).
> [!TIP]
> For more details, see the [Context Menu](../tutorial/context-menu.md) guide.
#### `menu.closePopup([window])`
* `window` [BaseWindow](base-window.md) (optional) - Default is the focused window.
- `window` [BaseWindow](base-window.md) (optional) - Default is the focused window.
Closes the context menu in the `window`.
#### `menu.append(menuItem)`
* `menuItem` [MenuItem](menu-item.md)
- `menuItem` [MenuItem](menu-item.md)
Appends the `menuItem` to the menu.
#### `menu.getMenuItemById(id)`
* `id` string
- `id` string
Returns `MenuItem | null` the item with the specified `id`
#### `menu.insert(pos, menuItem)`
* `pos` Integer
* `menuItem` [MenuItem](menu-item.md)
- `pos` Integer
- `menuItem` [MenuItem](menu-item.md)
Inserts the `menuItem` to the `pos` position of the menu.
@ -133,7 +139,7 @@ Objects created with `new Menu` or returned by `Menu.buildFromTemplate` emit the
Returns:
* `event` Event
- `event` Event
Emitted when `menu.popup()` is called.
@ -141,7 +147,7 @@ Emitted when `menu.popup()` is called.
Returns:
* `event` Event
- `event` Event
Emitted when a popup is closed either manually or with `menu.closePopup()`.
@ -153,296 +159,5 @@ Emitted when a popup is closed either manually or with `menu.closePopup()`.
A `MenuItem[]` array containing the menu's items.
Each `Menu` consists of multiple [`MenuItem`](menu-item.md)s and each `MenuItem`
can have a submenu.
## Examples
An example of creating the application menu with the simple template API:
```js @ts-expect-error=[107]
const { app, Menu } = require('electron')
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)
```
### Render process
To create menus initiated by the renderer process, send the required
information to the main process using IPC and have the main process display the
menu on behalf of the renderer.
Below is an example of showing a menu when the user right clicks the page:
```js @ts-expect-error=[21]
// renderer
window.addEventListener('contextmenu', (e) => {
e.preventDefault()
ipcRenderer.send('show-context-menu')
})
ipcRenderer.on('context-menu-command', (e, command) => {
// ...
})
// main
ipcMain.on('show-context-menu', (event) => {
const template = [
{
label: 'Menu Item 1',
click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
},
{ type: 'separator' },
{ label: 'Menu Item 2', type: 'checkbox', checked: true }
]
const menu = Menu.buildFromTemplate(template)
menu.popup({ window: BrowserWindow.fromWebContents(event.sender) })
})
```
## Notes on macOS Application Menu
macOS has a completely different style of application menu from Windows and
Linux. Here are some notes on making your app's menu more native-like.
### Standard Menus
On macOS there are many system-defined standard menus, like the [`Services`](https://developer.apple.com/documentation/appkit/nsapplication/1428608-servicesmenu?language=objc) and
`Windows` menus. To make your menu a standard menu, you should set your menu's
`role` to one of the following and Electron will recognize them and make them
become standard menus:
* `window`
* `help`
* `services`
### Standard Menu Item Actions
macOS has provided standard actions for some menu items, like `About xxx`,
`Hide xxx`, and `Hide Others`. To set the action of a menu item to a standard
action, you should set the `role` attribute of the menu item.
### Main Menu's Name
On macOS the label of the application menu's first item is always your app's
name, no matter what label you set. To change it, modify your app bundle's
`Info.plist` file. See
[About Information Property List Files][AboutInformationPropertyListFiles]
for more information.
### Menu Sublabels
Menu sublabels, or [subtitles](https://developer.apple.com/documentation/appkit/nsmenuitem/subtitle?language=objc), can be added to menu items using the `sublabel` option. Below is an example based on the renderer example above:
```js @ts-expect-error=[12]
// main
ipcMain.on('show-context-menu', (event) => {
const template = [
{
label: 'Menu Item 1',
sublabel: 'Subtitle 1',
click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
},
{ type: 'separator' },
{ label: 'Menu Item 2', sublabel: 'Subtitle 2', type: 'checkbox', checked: true }
]
const menu = Menu.buildFromTemplate(template)
menu.popup({ window: BrowserWindow.fromWebContents(event.sender) })
})
```
## Setting Menu for Specific Browser Window (_Linux_ _Windows_)
The [`setMenu` method][setMenu] of browser windows can set the menu of certain
browser windows.
## Menu Item Position
You can make use of `before`, `after`, `beforeGroupContaining`, `afterGroupContaining` and `id` to control how the item will be placed when building a menu with `Menu.buildFromTemplate`.
* `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` - 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` - 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` - 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:
```js
[
{ id: '1', label: 'one' },
{ id: '2', label: 'two' },
{ id: '3', label: 'three' },
{ id: '4', label: 'four' }
]
```
Menu:
```sh
- 1
- 2
- 3
- 4
```
Template:
```js
[
{ 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:
```sh
- 3
- 4
- ---
- 1
- ---
- 2
```
Template:
```js
[
{ id: '1', label: 'one', after: ['3'] },
{ id: '2', label: 'two', before: ['1'] },
{ id: '3', label: 'three' }
]
```
Menu:
```sh
- ---
- 3
- 2
- 1
```
[AboutInformationPropertyListFiles]: https://developer.apple.com/library/ios/documentation/general/Reference/InfoPlistKeyReference/Articles/AboutInformationPropertyListFiles.html
[setMenu]: browser-window.md#winsetmenumenu-linux-windows
Each `Menu` consists of multiple [`MenuItem`](menu-item.md) instances and each `MenuItem`
can nest a `Menu` into its `submenu` property.

View file

@ -2,5 +2,5 @@
* `type` string - The type of the event, can be `rawKeyDown`, `keyDown`, `keyUp` or `char`.
* `keyCode` string - The character that will be sent
as the keyboard event. Should only use the valid key codes in
[Accelerator](../accelerator.md).
as the keyboard event. Should only use valid [Accelerator](../../tutorial/keyboard-shortcuts.md#accelerators)
key codes.

View file

@ -8,7 +8,7 @@ Process: [Main](../glossary.md#main-process)
`Tray` is an [EventEmitter][event-emitter].
```js
```js title='Creating a basic tray menu'
const { app, Menu, Tray } = require('electron')
let tray = null
@ -25,6 +25,9 @@ app.whenReady().then(() => {
})
```
> [!TIP]
> See also: [A detailed guide about how to implement Tray menus](../tutorial/tray.md).
> [!WARNING]
> Electron's built-in classes cannot be subclassed in user code.
> For more information, see [the FAQ](../faq.md#class-inheritance-does-not-work-with-electron-built-in-modules).
@ -329,3 +332,47 @@ The `bounds` of this tray icon as `Object`.
Returns `boolean` - Whether the tray icon is destroyed.
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
## Platform considerations
### Linux
* Tray icon uses [StatusNotifierItem](https://www.freedesktop.org/wiki/Specifications/StatusNotifierItem/)
by default, when it is not available in user's desktop environment the
`GtkStatusIcon` will be used instead.
* The `click` event is emitted when the tray icon receives activation from
user, however the StatusNotifierItem spec does not specify which action would
cause an activation, for some environments it is left mouse click, but for
some it might be double left mouse click.
* In order for changes made to individual `MenuItem`s to take effect,
you have to call `setContextMenu` again. For example:
```js
const { app, Menu, Tray } = require('electron')
let appIcon = null
app.whenReady().then(() => {
appIcon = new Tray('/path/to/my/icon')
const contextMenu = Menu.buildFromTemplate([
{ label: 'Item1', type: 'radio' },
{ label: 'Item2', type: 'radio' }
])
// Make a change to the context menu
contextMenu.items[1].checked = false
// Call this again for Linux because we modified the context menu
appIcon.setContextMenu(contextMenu)
})
```
### macOS
* Icons passed to the Tray constructor should be [Template Images](native-image.md#template-image-macos).
* To make sure your icon isn't grainy on retina monitors, be sure your `@2x` image is 144dpi.
* If you are bundling your application (e.g., with webpack for development), be sure that the file names are not being mangled or hashed. The filename needs to end in Template, and the `@2x` image needs to have the same filename as the standard image, or MacOS will not magically invert your image's colors or use the high density image.
* 16x16 (72dpi) and 32x32@2x (144dpi) work well for most icons.
### Windows
* It is recommended to use `ICO` icons to get best visual effects.

View file

@ -67,7 +67,7 @@ Sets the maximum and minimum pinch-to-zoom level.
> [!NOTE]
> Visual zoom only applies to pinch-to-zoom behavior. Cmd+/-/0 zoom shortcuts are
> controlled by the 'zoomIn', 'zoomOut', and 'resetZoom' MenuItem roles in the application
> Menu. To disable shortcuts, manually [define the Menu](./menu.md#examples) and omit zoom roles
> Menu. To disable shortcuts, manually [define the Menu](../tutorial/menus.md) and omit zoom roles
> from the definition.
### `webFrame.setSpellCheckProvider(language, provider)`