Saltar al contenido principal

Notification

Crea las notificaciones de escritorio del sistema operativo

Proceso: principal</0>

Renderer process notifications

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

Clase: Notification

Crea las notificaciones de escritorio del sistema operativo

Proceso: principal</0>

Notification es un EventEmitter.

Crea una nueva Notification con propiedades nativas como las configuradas por options.

Métodos Estáticos

La clase Notification tiene los siguientes métodos estáticos:

Notification.isSupported()

Devuelve boolean - Si las notificaciones de escritorio son soportadas o no en el sistema actual

new Notification([options])

  • options Object (opcional)
    • 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 (opcional) macOS - Un subtítulo para la notificación, la cual aparecerá debajo del título.
    • body string (opcional) - El texto del cuerpo de la notificación, el cual será mostrado debajo del título o del subtítulo.
    • silent boolean (optional) - Whether or not to suppress the OS notification noise when showing the notification.
    • icon (string | NativeImage) (opcional) - Icono para usar en la notificación.
    • hasReply boolean (opcional) macOS - Si se agrega o no una opción de respuesta insertada en la notificación.
    • timeoutType string (opcional) Linux Windows - La duración del tiempo de espera de la notificación. Puede ser 'default' o 'never'.
    • replyPlaceholder string (opcional) macOS - El marcador de posición para escribir en el campo insertado de entrada de respuesta.
    • sound string (opcional) macOS - El nombre del archivo de sonido que se reproduce cuando se muestra la notificación.
    • urgency string (opcional) Linux - El nivel de urgencia de la notificación. Puede ser 'normal', 'critical', o 'low'.
    • actions NotificationAction[] (opcional) macOS - Las acciones que se añaden a la notificación. Por favor lea las acciones disponibles y limitaciones en la documentación de NotificationAction.
    • closeButtonText string (opcional) macOS - Un título personalizado para el botón cerrar de una alerta. Una cadena vacía hará que se utilice el texto localizado predeterminado.
    • toastXml string (opcional) Windows - Una descripción personalizada de la notificación en Windows sustituyendo todas las propiedades anteriores. Ofrece una personalización completa del diseño y el comportamiento de la notificación.

Eventos de Instancia

Los objetos creados con new Notification emite los siguientes eventos:

info

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

Evento: "show"

Devuelve:

  • 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.

Evento: "click"

Devuelve:

  • event

Se emite cuando el usuario hace clic en la notificación.

Evento: "close"

Devuelve:

  • event

Se emite cuando se cierra la notificación por medio de la intervención manual del usuario.

No se garantiza que este evento se emita en todos los casos donde se cierre la notificación.

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.

Evento: "reply" macOS

Devuelve:

  • event
  • reply string - La cadena que ingreso el usuario dentro del campo de respuesta insertado.

Se emite cuando el usuario hace clic en el botón "Reply" en una notificación con hasReply: true.

Evento: "action" macOS

Devuelve:

  • event
  • index númerp - El indice de la acción que fue activado.

Evento: 'failed' Windows

Devuelve:

  • event
  • error string - El error encontrado durante la ejecución del método show().

Se emite cuando un error ocurre mientras se esta creando y mostrando una notificación nativa.

Métodos de Instancia

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.

Si la notificación ha sido mostrada con anterioridad, este método descartará la notificación previa y creará una nueva con propiedades idénticas.

notification.close()

Descarta la notificación.

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.

Propiedades de la instancia

notification.title

Una propiedad string que representa el título de la notificación.

notification.subtitle

Una propiedad string que representa el subtítulo de la notificación.

notification.body

Una propiedad string que representa el cuerpo de la notificación.

notification.replyPlaceholder

Una propiedad string que representa el marcador de respuesta de la notificación.

notification.sound

Una propiedad string que representa el sonido de la notificación.

notification.closeButtonText

Una propiedad string que representa el texto del botón cerrar en la notificación.

notification.silent

Una propiedad boolean que representa si la notificación es silenciosa.

notification.hasReply

Una propiedad boolean que representa si al notificación tiene a una acción de respuesta.

notification.urgency Linux

Un propiedad string que representa el nivel de prioridad de la notificación. Puede ser 'normal', 'critical', o 'low'.

Por defecto es 'low' - vea NotifyUrgency para más información.

notification.timeoutType Linux Windows

Una propiedad string que representa el tipo de tiempo de espera para la notificación. Puede ser 'default' o 'never'.

Si timeoutType es especificado como 'never', la notificación nunca expirará. Se queda abierta hasta que se cierra por el llamado de la API o del usuario.

notification.actions

Una propiedad NotificationAction[] que representa las acciones de la notificación.

notification.toastXml Windows

Una propiedad string que representa el Toast XML de la notificación.

Reproducción de Sonidos

En macOS, se puede especificar el nombre del sonido que se desee reproducir cuando se muestre la notificación. Cualquier sonido por defecto (en Preferencias del sistema > Sonido) pueden ser usados en adición a los sonidos personalizados del sistema. Asegúrese de que el archivo de sonido sea copiado en el paquete de la aplicación (por ejemplo, YourApp.app/Contents/Resources), o uno de los siguientes direcciones:

  • ~/Library/Sounds
  • /Library/Sounds
  • /Network/Library/Sounds
  • /System/Library/Sounds

Ver la documentación NSSound para más información.