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

Tray

Class: Tray​

Добавить иконки и контекстные меню в системную область уведомлений.

Process: Main

Tray является EventEmitter'ом.

const { app, Menu, Tray } = require('electron')

let tray = null
app.whenReady().then(() => {
tray = new Tray('/path/to/my/icon')
const contextMenu = Menu.buildFromTemplate([
{ label: 'Item1', type: 'radio' },
{ label: 'Item2', type: 'radio' },
{ label: 'Item3', type: 'radio', checked: true },
{ label: 'Item4', type: 'radio' }
])
tray.setToolTip('This is my application.')
tray.setContextMenu(contextMenu)
})

Platform Considerations

Linux

  • Tray icon uses 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 MenuItems to take effect, you have to call setContextMenu again. Например:
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.
  • 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. Имя файла должно заканчиваться на Template, а изображение @2x должно иметь то же имя файла, что и стандартное изображение, иначе macOS не будет магически инвертировать цвета вашего изображения или использовать изображение с высокой плотностью.
  • 16x16 (72dpi) и 32x32@2x (144dpi) хорошо подходят для большинства значков.

Windows

  • Для получения наилучших визуальных эффектов рекомендуется использовать иконки ICO.

new Tray(image, [guid])​

  • image (NativeImage | string)
  • guid строка (необязательно) Windows — назначает идентификатор GUID значку в области уведомлений. If the executable is signed and the signature contains an organization in the subject line then the GUID is permanently associated with that signature. OS level settings like the position of the tray icon in the system tray will persist even if the path to the executable changes. If the executable is not code-signed then the GUID is permanently associated with the path to the executable. Changing the path to the executable will break the creation of the tray icon and a new GUID must be used. However, it is highly recommended to use the GUID parameter only in conjunction with code-signed executable. If an App defines multiple tray icons then each icon must use a separate GUID.

Создаёт новую иконку в трее, связанную с image.

События экземпляра​

Модуль Tray генерирует следующие события:

Событие: 'click'​

Возвращает:

Вызывается при двойном клике на иконке в трее.

Note that on Linux this event is emitted when the tray icon receives an activation, which might not necessarily be left mouse click.

Событие: 'right-click' macOS Windows​

Возвращает:

Возникает при правом клике на иконке в трее.

Событие: 'double-click' macOS Windows​

Возвращает:

Вызывается при двойном нажатии на иконку в трее.

Event: 'middle-click' Windows​

Возвращает:

Emitted when the tray icon is middle clicked.

Событие: 'balloon-show' Windows​

Возникает при всплывающем сообщении в трее.

Событие: 'balloon-click' Windows​

Вызывается при клике на всплывающем сообщении в трее.

Событие: 'balloon-closed' Windows​

Возникает, когда всплывающее сообщение в трее закрыто из-за тайм-аута или вручную пользователем.

Событие: 'drop' macOS​

Возникает при перетаскивании элементов на значок в трее.

Событие: 'drop-files' macOS​

Возвращает:

  • Событие типа event
  • files string[] - пути брошенных файлов.

Возникает при перетаскивании файлов на значок в трее.

Событие: 'drop-text' macOS​

Возвращает:

  • Событие типа event
  • text string - брошенная текстовая строка.

Возникает при перетаскивании строки на значок в трее.

Событие: 'drag-enter' macOS​

Возникает, когда операция перетаскивания происходит на иконке в трее.

Событие: 'drag-leave' macOS​

Возникает, когда операция перетаскивания завершилась на иконке в трее.

Событие: 'drag-end' macOS​

Возникает, когда операция перетаскивания заканчивается в трее или заканчивается в другом месте.

Event: 'mouse-up' macOS​

Возвращает:

Emitted when the mouse is released from clicking the tray icon.

Note: This will not be emitted if you have set a context menu for your Tray using tray.setContextMenu, as a result of macOS-level constraints.

Event: 'mouse-down' macOS​

Возвращает:

Emitted when the mouse clicks the tray icon.

Event: 'mouse-enter' macOS Windows​

Возвращает:

Возникает при входе курсора мыши на иконку в трее.

Event: 'mouse-leave' macOS Windows​

Возвращает:

Возникает при выходе курсора мыши с иконки в трее.

Событие: 'mouse-move' macOS Windows​

Возвращает:

Возникает при перемещении мыши на значке в трее.

Методы экземпляра​

Класс Tray имеет следующие методы:

tray.destroy()​

Немедленно уничтожить иконку в трее.

tray.setImage(image)​

Устанавливает image ассоциированный с значком в трее.

tray.setPressedImage(image) macOS​

Устанавливает image, связанное с этим значком в трее, при нажатии в macOS.

tray.setToolTip(toolTip)​

  • toolTip string

Устанавливает текст отображаемый при наведении на значок в трее.

tray.setTitle(title[, options]) macOS​

  • title string
  • options Object (опционально)
    • fontType string (опционально) - Вариант семейства шрифтов для отображения, может быть моноширинным или цифро-моноширинным. monospaced is available in macOS 10.15+ When left blank, the title uses the default system font.

Устанавливает заголовок, отображаемый рядом со значком в строке состояния (поддержка ANSI цветов).

tray.getTitle() macOS​

Возвращает string - заголовок, отображаемый рядом со значком в области уведомлений в строке состояния

tray.setIgnoreDoubleClickEvents(ignore) macOS​

  • ignore логическое значение

Sets the option to ignore double click events. Ignoring these events allows you to detect every individual click of the tray icon.

Значение по умолчанию установлено в значение false.

tray.getIgnoreDoubleClickEvents() macOS​

Возвращает boolean - будет ли игнорироваться события двойного щелчка.

tray.displayBalloon(options) Windows​

  • options Object
    • icon (NativeImage | string) (optional) - Icon to use when iconType is custom.
    • iconType string (optional) - Can be none, info, warning, error or custom. По умолчанию custom.
    • title string
    • content string
    • largeIcon boolean (optional) - The large version of the icon should be used. По умолчанию - true. Maps to NIIF_LARGE_ICON.
    • noSound boolean (опционально) - Не проигрывать соответствующий звук. По умолчанию - false. Maps to NIIF_NOSOUND.
    • respectQuietTime boolean (optional) - Do not display the balloon notification if the current user is in "quiet time". По умолчанию - false. Maps to NIIF_RESPECT_QUIET_TIME.

Отображает всплывающее сообщение в трее.

tray.removeBalloon() Windows​

Удаляет всплывающее уведомление в трее.

tray.focus() Windows​

Возвращает фокус в область уведомления панели задач. Notification area icons should use this message when they have completed their UI operation. For example, if the icon displays a shortcut menu, but the user presses ESC to cancel it, use tray.focus() to return focus to the notification area.

tray.popUpContextMenu([menu, position]) macOS Windows​

  • menu Menu (опционально)
  • position Point (optional) - The pop up position.

Pops up the context menu of the tray icon. When menu is passed, the menu will be shown instead of the tray icon's context menu.

position доступна только для Windows, и это (0, 0) по умолчанию.

tray.closeContextMenu() macOS Windows​

Closes an open context menu, as set by tray.setContextMenu().

tray.setContextMenu(menu)​

  • menu Menu | null

Устанавливает контекстное меню для этого значка.

tray.getBounds() macOS Windows​

Returns Rectangle

bounds значка в трее как Object.

tray.isDestroyed()​

Возвращает boolean - уничтожен ли значок в трее.