Перейти к основному содержанию

MenuItem

Class: MenuItem

Добавляет элементы в основное меню и контекстное меню приложения.

Process: Main

See Menu for examples.

[!WARNING] Electron's built-in classes cannot be subclassed in user code. For more information, see the FAQ.

new MenuItem(options)

  • options Object
    • click Function (optional) - Will be called with click(menuItem, window, event) when the menu item is clicked.
      • menuItem MenuItem
      • window BaseWindow | undefined - This will not be defined if no window is open.
      • event KeyboardEvent
    • 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.
    • type string (опционально)
      • normal
      • separator
      • submenu
      • флажок
      • radio
      • header - Only available on macOS 14 and up.
      • palette - Only available on macOS 14 and up.
    • label string (опционально)
    • sublabel string (optional) macOS - Available in macOS >= 14.4
    • toolTip string (опционально) macOS - Текст при наведении на этот пункт меню.
    • accelerator string (optional) - An Accelerator string.
    • icon (NativeImage | string) (optional)
    • enabled boolean (опционально) - Если false, пункт меню выделится серым цветом и не будет нажимться.
    • acceleratorWorksWhenHidden boolean (optional) macOS - default is true, and when false will prevent the accelerator from triggering the item if the item is not visible.
    • visible boolean (опционально) - Если false, пункт меню будет полностью скрыт.
    • checked boolean (опционально) - Должно быть указано только для checkbox или radio типов элементов меню.
    • registerAccelerator boolean (optional) Linux Windows - If false, the accelerator won't be registered with the system, but it will still be displayed. Defaults to true.
    • sharingItem SharingItem (optional) macOS - The item to share when the role is shareMenu.
    • submenu (MenuItemConstructorOptions[] | Menu) (опционально) - Необходимо указать для submenu типы элементов меню. Если submenu указано, то type: 'submenu' может быть опущен. Если значение не является Menu то оно будет автоматически преобразовано в значение Menu.buildFromTemplate.
    • id string (optional) - Unique within a single menu. If defined then it can be used as a reference to this item by the position attribute.
    • before string[] (optional) - Inserts this item before the item with the specified id. Если указанный элемент не существует, то элемент будет вставлен в конец меню. Кроме того, подразумевается, что рассматриваемый элемент меню размещен в той же "группе", что и сам элемент.
    • after string[] (optional) - Inserts this item after the item with the specified id. Если ссылаемый элемент не существует, тогда элемент будет вставлен в конец меню.
    • beforeGroupContaining string[] (optional) - 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 string[] (optional) - 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.
примечание

acceleratorWorksWhenHidden is specified as being macOS-only because accelerators always work when items are hidden on Windows and Linux. Эта опция доступна пользователям для того, чтобы дать им возможность отключить ее, так как это возможно в родной macOS разработке.

Свойства экземпляра

Для экземпляров MenuItem доступны следующие свойства:

A string indicating the item's unique id. This property can be dynamically changed.

A string indicating the item's visible label.

A Function that is fired when the MenuItem receives a click event. It can be called with menuItem.click(event, focusedWindow, focusedWebContents).

Menu (опционально), содержащие подменю пункты, если таковые имеются.

A string indicating the type of the item. Can be normal, separator, submenu, checkbox, radio, header or palette.

примечание

header and palette are only available on macOS 14 and up.

string (опционально) с указанием роли элемента, если установлено. 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, startSpeaking, stopSpeaking, zoom, front, appMenu, fileMenu, editMenu, viewMenu, shareMenu, recentDocuments, toggleTabBar, selectNextTab, selectPreviousTab, showAllTabs, mergeAllWindows, clearRecentDocuments, moveTabToNewWindow or windowMenu

An Accelerator (optional) indicating the item's accelerator, if set.

An Accelerator | null indicating the item's user-assigned accelerator for the menu item.

[!NOTE] This property is only initialized after the MenuItem has been added to a Menu. Either via Menu.buildFromTemplate or via Menu.append()/insert(). Accessing before initialization will just return null.

A NativeImage | string (optional) indicating the item's icon, if set.

A string indicating the item's sublabel.

A string indicating the item's hover text.

A boolean indicating whether the item is enabled. This property can be dynamically changed.

A boolean indicating whether the item is visible. This property can be dynamically changed.

A boolean indicating whether the item is checked. This property can be dynamically changed.

Элемент меню checkbox будет включать и выключать свойство checked при его выборе.

Radio пункт меню включит его свойство checked при нажатии, и отключит это свойство для всех смежных пунктов в том же меню.

Вы можете добавить функцию click для дополнительного поведения.

A boolean indicating if the accelerator should be registered with the system or just displayed.

This property can be dynamically changed.

A SharingItem indicating the item to share when the role is shareMenu.

This property can be dynamically changed.

A number indicating an item's sequential unique id.

Меню, частью которого является элемент.