Notificaciones
Envía notificaciones nativas al usuario utilizando el plugin de notificaciones.
Plataformas soportadas
This plugin requires a Rust version of at least 1.77.2
Platform | Level | Notes |
---|---|---|
windows | Only works for installed apps. Shows powershell name & icon in development. | |
linux | ||
macos | ||
android | ||
ios |
Configuración
Instala el plugin de notificaciones para comenzar.
Utiliza el gestor de paquetes de tu proyecto para añadir la dependencia:
npm run tauri add notification
yarn run tauri add notification
pnpm tauri add notification
deno task tauri add notification
bun tauri add notification
cargo tauri add notification
-
Ejecuta el siguiente comando en el directorio
src-tauri
para añadir el plugin a las dependencias del proyecto enCargo.toml
:cargo add tauri-plugin-notification -
Modifica
lib.rs
para inicializar el plugin:src-tauri/src/lib.rs #[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {tauri::Builder::default().plugin(tauri_plugin_notification::init()).run(tauri::generate_context!()).expect("error while running tauri application");} -
Si deseas utilizar notificaciones desde JavaScript, instala también el paquete npm:
npm install @tauri-apps/plugin-notificationyarn add @tauri-apps/plugin-notificationpnpm add @tauri-apps/plugin-notificationbun add npm:@tauri-apps/plugin-notificationbun add @tauri-apps/plugin-notification
Uso
Aquí hay algunos ejemplos de cómo usar el plugin de notificaciones:
- Enviar notificaciones a los usuarios
- Añadir una acción a una notificación
- Añadir un adjunto a una notificación
- Enviar una notificación a un canal específico
El plugin de notificaciones está disponible tanto en JavaScript como en Rust.
Enviar notificación
Sigue estos pasos para enviar una notificación:
-
Comprueba si se ha concedido el permiso
-
Solicita permiso si no se ha concedido
-
Envía la notificación
import { isPermissionGranted, requestPermission, sendNotification,} from '@tauri-apps/plugin-notification';// si se usa `"withGlobalTauri": true`, puedes hacer// const { isPermissionGranted, requestPermission, sendNotification, } = window.__TAURI__.notification;
// Tienes permiso para enviar una notificación?let permissionGranted = await isPermissionGranted();
// Si no es así, necesitamos solicitarloif (!permissionGranted) { const permission = await requestPermission(); permissionGranted = permission === 'granted';}
// Una vez que se concede el permiso, envía la notificaciónif (permissionGranted) { sendNotification({ title: 'Tauri', body: 'Tauri is awesome!' });}
tauri::Builder::default() .plugin(tauri_plugin_notification::init()) .setup(|app| { use tauri_plugin_notification::NotificationExt; app.notification() .builder() .title("Tauri") .body("Tauri es genial") .show() .unwrap();
Ok(()) }) .run(tauri::generate_context!()) .expect("error mientras se ejecutaba la aplicación tauri");
Actions
Las acciones añaden botones e inputs interactivos a las notificaciones. Úsalas para crear una experiencia interactiva para tus usuarios.
Registrar tipos de acciones
Registra tipos de acciones para definir elementos interactivos:
import { registerActionTypes } from '@tauri-apps/plugin-notification';
await registerActionTypes([ { id: 'messages', actions: [ { id: 'reply', title: 'Responder', input: true, inputButtonTitle: 'Enviar', inputPlaceholder: 'Escribe tu respuesta...', }, { id: 'mark-read', title: 'Marcar como leído', foreground: false, }, ], },]);
Propiedades de las acciones
Propiedad | Descripción |
---|---|
id | Identificador único de la acción |
title | Texto a mostrar en la acción del botón |
requiresAuthentication | Requiere autenticación en el dispositivo |
foreground | Pone la aplicación en primer plano cuando es accionada |
destructive | Muestra la acción en rojo en iOS |
input | Habilita el campo de texto |
inputButtonTitle | Texto para el botón para enviar el input |
inputPlaceholder | Texto de ejemplo en el campo de texto |
Suscribirse a acciones
Suscribirse a notificaciones con acciones:
import { onAction } from '@tauri-apps/plugin-notification';
await onAction((notification) => { console.log('Acción realizada:', notification);});
Adjuntos
Los adjuntos añaden contenido multimedia a las notificaciones. El soporte varía según la plataforma.
import { sendNotification } from '@tauri-apps/plugin-notification';
sendNotification({ title: 'Nueva imagen', body: 'Mira esta imagen', attachments: [ { id: 'image-1', url: 'asset:///notification-image.jpg', }, ],});
Propiedades de los adjuntos
Propiedad | Descripción |
---|---|
id | Identificador único |
url | URL del contenido usando los protocolos asset:// o file:// |
Nota: Prueba los adjuntos en tus plataformas que quieras soportar para asegurarte de su compatibilidad.
Canales
Los canales organizan las notificaciones en categorías con diferentes comportamientos. Aunque se usan principalmente en Android, proporcionan una API consistente en todas las plataformas.
Crear un canal
import { createChannel, Importance, Visibility,} from '@tauri-apps/plugin-notification';
await createChannel({ id: 'messages', name: 'Mensajes', description: 'Notificaciones para nuevos mensajes', importance: Importance.High, visibility: Visibility.Private, lights: true, lightColor: '#ff0000', vibration: true, sound: 'notification_sound',});
Propiedades de los canales
Propiedad | Descripción |
---|---|
id | Identificador único |
name | Nombre a mostrar |
description | Propósito del canal |
importance | Nivel de prioridad (None, Min, Low, Default, High) |
visibility | Nivel de privacidad (Secret, Private, Public) |
lights | Habilitar indicador LED (Android) |
lightColor | Color del indicador LED (Android) |
vibration | Habilitar vibraciones |
sound | Nombre del fichero para sonido personalizado |
Gestionar canales
Listar canales existentes:
import { channels } from '@tauri-apps/plugin-notification';
const existingChannels = await channels();
Eliminar un canal:
import { removeChannel } from '@tauri-apps/plugin-notification';
await removeChannel('messages');
Usando canales
Enviar una notificación usando un canal:
import { sendNotification } from '@tauri-apps/plugin-notification';
sendNotification({ title: 'Nuevo mensaje', body: 'Tienes un nuevo mensaje', channelId: 'messages',});
Nota: Crea canales antes de enviar notificaciones que los referencien. Los identificadores de canal inválidos impiden que las notificaciones se muestren.
Consideraciones de seguridad
Aparte de los procedimientos normales de sanitización de la entrada del usuario, actualmente no hay consideraciones de seguridad conocidas.
Default Permission
This permission set configures which notification features are by default exposed.
Granted Permissions
It allows all notification related features.
allow-is-permission-granted
allow-request-permission
allow-notify
allow-register-action-types
allow-register-listener
allow-cancel
allow-get-pending
allow-remove-active
allow-get-active
allow-check-permissions
allow-show
allow-batch
allow-list-channels
allow-delete-channel
allow-create-channel
allow-permission-state
Permission Table
Identifier | Description |
---|---|
|
Enables the batch command without any pre-configured scope. |
|
Denies the batch command without any pre-configured scope. |
|
Enables the cancel command without any pre-configured scope. |
|
Denies the cancel command without any pre-configured scope. |
|
Enables the check_permissions command without any pre-configured scope. |
|
Denies the check_permissions command without any pre-configured scope. |
|
Enables the create_channel command without any pre-configured scope. |
|
Denies the create_channel command without any pre-configured scope. |
|
Enables the delete_channel command without any pre-configured scope. |
|
Denies the delete_channel command without any pre-configured scope. |
|
Enables the get_active command without any pre-configured scope. |
|
Denies the get_active command without any pre-configured scope. |
|
Enables the get_pending command without any pre-configured scope. |
|
Denies the get_pending command without any pre-configured scope. |
|
Enables the is_permission_granted command without any pre-configured scope. |
|
Denies the is_permission_granted command without any pre-configured scope. |
|
Enables the list_channels command without any pre-configured scope. |
|
Denies the list_channels command without any pre-configured scope. |
|
Enables the notify command without any pre-configured scope. |
|
Denies the notify command without any pre-configured scope. |
|
Enables the permission_state command without any pre-configured scope. |
|
Denies the permission_state command without any pre-configured scope. |
|
Enables the register_action_types command without any pre-configured scope. |
|
Denies the register_action_types command without any pre-configured scope. |
|
Enables the register_listener command without any pre-configured scope. |
|
Denies the register_listener command without any pre-configured scope. |
|
Enables the remove_active command without any pre-configured scope. |
|
Denies the remove_active command without any pre-configured scope. |
|
Enables the request_permission command without any pre-configured scope. |
|
Denies the request_permission command without any pre-configured scope. |
|
Enables the show command without any pre-configured scope. |
|
Denies the show command without any pre-configured scope. |
© 2025 Tauri Contributors. CC-BY / MIT