Saltar al contenido

Notificaciones

GitHubnpmcrates.io
Referencia de API

Envía notificaciones nativas a tu usuario utilizando el plugin de notificaciones.

Este plugin requiere una versión de Rust de al menos 1.77.2

PlataformaNivelNotas
windows

Solo funciona para aplicaciones instaladas. Muestra el nombre e ícono de powershell en desarrollo.

linux
macos
android
ios

Instala el plugin de notificaciones para comenzar.

Usa el gestor de paquetes de tu proyecto para agregar la dependencia:

npm run tauri add notification

Aquí tienes algunos ejemplos de cómo usar el plugin de notificaciones:

El plugin de notificaciones está disponible tanto en JavaScript como en Rust.

Sigue estos pasos para enviar una notificación:

  1. Comprobar si el permiso está concedido

  2. Solicitar permiso si no está concedido

  3. Enviar la notificación

import {
isPermissionGranted,
requestPermission,
sendNotification,
} from '@tauri-apps/plugin-notification';
// when using `"withGlobalTauri": true`, you may use
// const { isPermissionGranted, requestPermission, sendNotification, } = window.__TAURI__.notification;
// Do you have permission to send a notification?
let permissionGranted = await isPermissionGranted();
// If not we need to request it
if (!permissionGranted) {
const permission = await requestPermission();
permissionGranted = permission === 'granted';
}
// Once permission has been granted we can send the notification
if (permissionGranted) {
sendNotification({ title: 'Tauri', body: 'Tauri is awesome!' });
}

Las acciones añaden botones e insumos interactivos a las notificaciones. Úsalas para crear una experiencia adaptable para tus usuarios.

Registra tipos de acción para definir elementos interactivos:

import { registerActionTypes } from '@tauri-apps/plugin-notification';
await registerActionTypes([
{
id: 'messages',
actions: [
{
id: 'reply',
title: 'Reply',
input: true,
inputButtonTitle: 'Send',
inputPlaceholder: 'Type your reply...',
},
{
id: 'mark-read',
title: 'Mark as Read',
foreground: false,
},
],
},
]);
Propiedad Descripción
id Identificador único para la acción
title Texto a mostrar para el botón de acción
requiresAuthentication Requiere autenticación del dispositivo
foreground Trae la app al primer plano cuando se activa
destructive Muestra la acción en rojo en iOS
input Habilita la entrada de texto
inputButtonTitle Texto para el botón de enviar entrada
inputPlaceholder Texto de marcador de posición para el campo de entrada

Escucha las interacciones del usuario con las acciones de notificación:

import { onAction } from '@tauri-apps/plugin-notification';
await onAction((notification) => {
console.log('Action performed:', notification);
});

Los archivos 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: 'New Image',
body: 'Check out this picture',
attachments: [
{
id: 'image-1',
url: 'asset:///notification-image.jpg',
},
],
});
Propiedad Descripción
id Identificador único
url URL del contenido usando el protocolo asset:// o file://

Nota: Prueba los archivos adjuntos en tus plataformas de destino para asegurar la compatibilidad.

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.

import {
createChannel,
Importance,
Visibility,
} from '@tauri-apps/plugin-notification';
await createChannel({
id: 'messages',
name: 'Messages',
description: 'Notifications for new messages',
importance: Importance.High,
visibility: Visibility.Private,
lights: true,
lightColor: '#ff0000',
vibration: true,
sound: 'notification_sound',
});
Propiedad Descripción
id Identificador único
name Nombre para mostrar
description Descripción del propósito
importance Nivel de prioridad (None, Min, Low, Default, High)
visibility Configuración de privacidad (Secret, Private, Public)
lights Habilitar LED de notificación (Android)
lightColor Color del LED (Android)
vibration Habilitar vibraciones
sound Nombre de archivo de sonido personalizado

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');

Enviar una notificación usando un canal:

import { sendNotification } from '@tauri-apps/plugin-notification';
sendNotification({
title: 'New Message',
body: 'You have a new message',
channelId: 'messages',
});

Nota: Crea canales antes de enviar notificaciones que los referencien. Los IDs de canal no válidos evitan que se muestren las notificaciones.

Aparte de los procedimientos normales de sanitización de la entrada del usuario, actualmente no hay consideraciones de seguridad conocidas.

Permiso Predeterminado

Este conjunto de permisos configura qué características de notificación se exponen por defecto.

Permisos Otorgados

Permite todas las características relacionadas con notificaciones.

Este conjunto de permisos predeterminado incluye lo siguiente:

  • 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

Tabla de Permisos

Identificador Descripción

notification:allow-batch

Habilita el comando batch sin ningún scope preconfigurado.

notification:deny-batch

Deniega el comando batch sin ningún scope preconfigurado.

notification:allow-cancel

Habilita el comando cancel sin ningún alcance preconfigurado.

notification:deny-cancel

Deniega el comando cancel sin ningún alcance preconfigurado.

notification:allow-check-permissions

Habilita el comando check_permissions sin ningún alcance preconfigurado.

notification:deny-check-permissions

Deniega el comando check_permissions sin ningún alcance preconfigurado.

notification:allow-create-channel

Habilita el comando create_channel sin ningún scope preconfigurado.

notification:deny-create-channel

Deniega el comando create_channel sin ningún scope preconfigurado.

notification:allow-delete-channel

Habilita el comando delete_channel sin ningún scope preconfigurado.

notification:deny-delete-channel

Deniega el comando delete_channel sin ningún scope preconfigurado.

notification:allow-get-active

Habilita el comando get_active sin ningún scope preconfigurado.

notification:deny-get-active

Deniega el comando get_active sin ningún scope preconfigurado.

notification:allow-get-pending

Habilita el comando get_pending sin ningún scope preconfigurado.

notification:deny-get-pending

Deniega el comando get_pending sin ningún scope preconfigurado.

notification:allow-is-permission-granted

Habilita el comando is_permission_granted sin ningún scope preconfigurado.

notification:deny-is-permission-granted

Deniega el comando is_permission_granted sin ningún scope preconfigurado.

notification:allow-list-channels

Habilita el comando list_channels sin ningún scope preconfigurado.

notification:deny-list-channels

Deniega el comando list_channels sin ningún scope preconfigurado.

notification:allow-notify

Habilita el comando notify sin ningún scope preconfigurado.

notification:deny-notify

Deniega el comando notify sin ningún scope preconfigurado.

notification:allow-permission-state

Habilita el comando permission_state sin ningún scope preconfigurado.

notification:deny-permission-state

Deniega el comando permission_state sin ningún scope preconfigurado.

notification:allow-register-action-types

Habilita el comando register_action_types sin ningún scope preconfigurado.

notification:deny-register-action-types

Deniega el comando register_action_types sin ningún scope preconfigurado.

notification:allow-register-listener

Habilita el comando register_listener sin ningún scope preconfigurado.

notification:deny-register-listener

Deniega el comando register_listener sin ningún scope preconfigurado.

notification:allow-remove-active

Habilita el comando remove_active sin ningún scope preconfigurado.

notification:deny-remove-active

Deniega el comando remove_active sin ningún scope preconfigurado.

notification:allow-request-permission

Habilita el comando request_permission sin ningún scope preconfigurado.

notification:deny-request-permission

Deniega el comando request_permission sin ningún scope preconfigurado.

notification:allow-show

Habilita el comando show sin ningún scope preconfigurado.

notification:deny-show

Deniega el comando show sin ningún scope preconfigurado.


© 2026 Colaboradores de Tauri. CC-BY / MIT