Class: MenuItem
Class: MenuItem
Добавляет элементы в основное меню и контекстное меню приложения.
Process: Main
See Menu for examples.
new MenuItem(options)
Примечание: acceleratorWorksWhenHidden указан только как macOS потому, что accelerators всегда работают, когда элементы скрыты в Windows и 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.
При задании role на macOS, label и accelerator являются единственными параметрами, которые влияют на пункт меню. Все остальные параметры будут проигнорированы. Нижний регистр role, например toggledevtools, все еще поддерживается.
Note: The enabled and visibility properties 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 or radio.
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 MenuItem has been added to a Menu. Either via Menu.buildFromTemplate or via Menu.append()/insert(). Accessing before initialization will just return null.
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
string с указанием текста, который появляется при наведении курсора на элемент.
menuItem.enabled
boolean указывает, включен ли элемент, это свойство может быть динамически изменено.
menuItem.visible
boolean указывает, видим ли элемент, это свойство может быть динамически изменено.
menuItem.checked
boolean указывает, помечен ли элемент флажком, это свойство может быть динамически изменено.
Элемент меню 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
Меню, частью которого является элемент.