Class: 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)
acceleratorWorksWhenHidden is specified as being macOS-only because accelerators always work when items are hidden on Windows and Linux. Эта опция доступна пользователям для того, чтобы дать им возможность отключить ее, так как это возможно в родной macOS разработке.
Роли
Роли позволяют элементам класса menu иметь заранее определенные поведения.
Лучше всего указать role для любого элемента меню, который соответствует стандартной роли, а не пытаться вручную реализовать поведение в функции click. Встроенное поведение role даст наилучшую нативную возможность использования.
Значения label и accelerator необязательны при использовании role и по умолчанию будут присваиваться для каждой для каждой платформы.
Каждый элемент меню должен иметь role или label, или в случае разделителя type.
Свойство role может иметь следующие значения:
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- Свернуть текущее окно.close- Закрыть текущее окно.quit- Выйти из приложения.reload- Перезагрузить текущее окно.forceReload- Перезагрузить текущее окно, игнорировать кэш.toggleDevTools- Включить инструмент разработчика для текущего окна.togglefullscreen-Включить полноэкранный режим для текущего окна.resetZoom- Сброс измененного масштаба страницы до исходного размера.zoomIn- Увеличение масштаба страницы на 10%.zoomOut- Уменьшение масштаба страницы на 10%.toggleSpellChecker- Enable/disable builtin spell checker.fileMenu- Полное меню "Файл" по умолчанию (Закрыть/Выйти)editMenu- Whole default "Edit" menu (Undo, Copy, etc.).viewMenu- Полное меню "Вид" по умолчанию (перезагрузка, переключение инструментов разработчика и т. д.)windowMenu- Полное меню "Окно" по умолчанию (Свернуть, масштаб и т. д.).
На macOS доступны следующие дополнительные роли:
appMenu- Полное меню "App" по умолчанию (О программе, службах и т. д.)hide- Map to thehideaction.hideOthers- Map to thehideOtherApplicationsaction.unhide- Map to theunhideAllApplicationsaction.showSubstitutions- Сопоставляется сorderFrontSubstitutionsPanel.toggleSmartQuotes- Сопоставляется сtoggleAutomaticQuoteSubstitution.toggleSmartDashes- Сопоставляется сtoggleAutomaticDashSubstitution.toggleTextReplacement- Сопоставляется сtoggleAutomaticTextReplacement.startSpeaking- Map to thestartSpeakingaction.stopSpeaking- Map to thestopSpeakingaction.front- Map to thearrangeInFrontaction.zoom- Map to theperformZoomaction.toggleTabBar- Map to thetoggleTabBaraction.selectNextTab- Map to theselectNextTabaction.selectPreviousTab- Map to theselectPreviousTabaction.showAllTabs- Map to theshowAllTabsaction.mergeAllWindows- Сопоставляется сmergeAllWindows.moveTabToNewWindow- Сопоставляется сmoveTabToNewWindow.window- Подменю в меню "Окно".help- Подменю в меню "Help".services- Подменю меню "Сервисы". 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- Подменю представляет собой меню "Открыть недавние".clearRecentDocuments- Сопоставляется сclearRecentDocuments.shareMenu- The submenu is share menu. ThesharingItemproperty 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
enabledandvisibilityproperties are not available for top-level menu items in the tray on macOS.
Свойства экземпляра
Для экземпляров MenuItem доступны следующие свойства:
menuItem.id
A string indicating the item's unique id, this property can be dynamically changed.
menuItem.label
A string indicating the item's visible label.
menuItem.click
A Function that is fired when the MenuItem receives a click event. It can be called with menuItem.click(event, focusedWindow, focusedWebContents).
eventKeyboardEventfocusedWindowBaseWindowfocusedWebContentsWebContents
menuItem.submenu
Menu (опционально), содержащие подменю пункты, если таковые имеются.
menuItem.type
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.
menuItem.role
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
menuItem.accelerator
An Accelerator (optional) indicating the item's accelerator, if set.
menuItem.userAccelerator Readonly macOS
An Accelerator | null indicating the item's user-assigned accelerator for the menu item.
[!NOTE] This property is only initialized after the
MenuItemhas been added to aMenu. Either viaMenu.buildFromTemplateor viaMenu.append()/insert(). Accessing before initialization will just returnnull.
menuItem.icon
A NativeImage | string (optional) indicating the item's icon, if set.
menuItem.sublabel
A string indicating the item's sublabel.
menuItem.toolTip macOS
A string indicating the item's hover text.
menuItem.enabled
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 dynamically changed.
menuItem.checked
A boolean indicating whether the item is checked, this property can be dynamically changed.
Элемент меню checkbox будет включать и выключать свойство checked при его выборе.
Radio пункт меню включит его свойство checked при нажатии, и отключит это свойство для всех смежных пунктов в том же меню.
Вы можете добавить функцию click для дополнительного поведения.
menuItem.registerAccelerator
A boolean indicating if the accelerator should be registered with the system or just displayed.
This property can be dynamically changed.
menuItem.sharingItem macOS
A SharingItem indicating the item to share when the role is shareMenu.
This property can be dynamically changed.
menuItem.commandId
A number indicating an item's sequential unique id.
menuItem.menu
Меню, частью которого является элемент.