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

Notification (Оповещения)

Создание уведомлений на рабочем столе ОС

Процесс: Главный

Renderer process notifications

If you want to show notifications from a renderer process you should use the web Notifications API

Class: Notification / Уведомление

Создание уведомлений на рабочем столе ОС

Процесс: Главный

Notification является EventEmitter.

Так создается новый экземпляр BrowserWindow с собственными свойствами, установленными в options.

Статические методы

Класс Notification имеет следующие статические методы:

Notification.isSupported()

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

new Notification([options])

  • options Object (опционально)
    • title string (optional) - A title for the notification, which will be displayed at the top of the notification window when it is shown.
    • subtitle string (опционально) macOS - Подзаголовок для уведомления, который будет отображаться под заголовком.
    • body string (optional) - The body text of the notification, which will be displayed below the title or subtitle.
    • silent boolean (optional) - Whether or not to suppress the OS notification noise when showing the notification.
    • icon (string | NativeImage) (опционально) - Значок для отображения в уведомлении.
    • hasReply boolean (опционально) macOS - Нужно ли добавлять встроенный ответ к уведомлению.
    • timeoutType string (optional) Linux Windows - The timeout duration of the notification. Can be 'default' or 'never'.
    • replyPlaceholder string (опционально) macOS - Заполнитель для записи в поле ввода встроенного ответа.
    • sound string (опционально) macOS - Имя звукового файла, воспроизводимого при отображении уведомления.
    • urgency string (optional) Linux - The urgency level of the notification. Can be 'normal', 'critical', or 'low'.
    • actions NotificationAction[] (опционально) macOS - Действия для добавления к уведомлению. Пожалуйста, прочитайте доступные действия и ограничения в документации NotificationAction.
    • closeButtonText string (optional) macOS - A custom title for the close button of an alert. An empty string will cause the default localized text to be used.
    • toastXml string (optional) Windows - A custom description of the Notification on Windows superseding all properties above. Provides full customization of design and behavior of the notification.

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

Объекты созданные с помощью new Notification имеют следующие события:

информация

Some events are only available on specific operating systems and are labeled as such.

Событие: 'show'

Возвращает:

  • Событие типа event

Emitted when the notification is shown to the user. Note that this event can be fired multiple times as a notification can be shown multiple times through the show() method.

Событие: 'click'

Возвращает:

  • Событие типа event

Возникает при нажатии на уведомление пользователя.

Событие: 'close'

Возвращает:

  • Событие типа event

Возникает при закрытии уведомления вручную пользователем.

Не гарантируется, что это событие будет отправлено во всех случаях, когда уведомление закрыто.

On Windows, the close event can be emitted in one of three ways: programmatic dismissal with notification.close(), by the user closing the notification, or via system timeout. If a notification is in the Action Center after the initial close event is emitted, a call to notification.close() will remove the notification from the action center but the close event will not be emitted again.

Событие: 'reply' macOS

Возвращает:

  • Событие типа event
  • reply string - Строка, введенная пользователем в поле ответа в строке ответа.

Возникает при нажатии пользователем кнопки "Ответить" в уведомлении с hasReply: true.

Событие: 'action' macOS

Возвращает:

  • Событие типа event
  • index number - Индекс действия, которое было активировано.

Event: 'failed' Windows

Возвращает:

  • Событие типа event
  • error string - The error encountered during execution of the show() method.

Emitted when an error is encountered while creating and showing the native notification.

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

Objects created with the new Notification() constructor have the following instance methods:

notification.show()

Immediately shows the notification to the user. Unlike the web notification API, instantiating a new Notification() does not immediately show it to the user. Instead, you need to call this method before the OS will display it.

Если уведомление было показано ранее, этот метод отклонит ранее показанное уведомление и создаст новое с идентичными свойствами.

notification.close()

Отклоняет уведомление.

On Windows, calling notification.close() while the notification is visible on screen will dismiss the notification and remove it from the Action Center. If notification.close() is called after the notification is no longer visible on screen, calling notification.close() will try remove it from the Action Center.

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

notification.title

Свойство string, представляющее заголовок уведомления.

notification.subtitle

Свойство string, представляющее подзаголовок уведомления.

notification.body

Свойство string, представляющее тело уведомления.

notification.replyPlaceholder

Свойство string, представляющее заполнитель ответа уведомления.

notification.sound

Свойство string, представляющее звук уведомления.

notification.closeButtonText

Свойство string, представляющее текст кнопки закрытия уведомления.

notification.silent

Свойство boolean, представляющее, является ли уведомление беззвучным.

notification.hasReply

Свойство boolean, представляющее, есть ли в уведомлении действие для ответа.

notification.urgency Linux

A string property representing the urgency level of the notification. Can be 'normal', 'critical', or 'low'.

Стандартное значение - 'low'. Что бы узнать подробнее, смотрите NotifyUrgency.

notification.timeoutType Linux Windows

A string property representing the type of timeout duration for the notification. Can be 'default' or 'never'.

If timeoutType is set to 'never', the notification never expires. It stays open until closed by the calling API or the user.

notification.actions

A NotificationAction[] свойство, представляющее действия уведомления.

notification.toastXml Windows

A string property representing the custom Toast XML of the notification.

Воспроизведение звуков

В macOS вы можете указать название звука, который вы хотели бы воспроизвести, когда отображается уведомление. Any of the default sounds (under System Preferences > Sound) can be used, in addition to custom sound files. Убедитесь, что звуковой файл скопирован в папку пакета приложений (например, YourApp.app/Contents/Resources), или в одно из следующих мест:

  • ~/Library/Sounds (~/Библиотека/Звуки)
  • /Library/Sounds (/Библиотека/Звуки)
  • /Network/Library/Sounds (/Сеть/Библиотека/Звуки)
  • /System/Library/Sounds (/Система/Библиотека/Звуки)

Смотрите документацию NSSound для получения дополнительной информации.