|
| 1 | +--- |
| 2 | +title: Notificaciones |
| 3 | +description: Envía notificaciones nativas al usuario. |
| 4 | +i18nReady: true |
| 5 | +plugin: notification |
| 6 | +--- |
| 7 | + |
| 8 | +import PluginLinks from '@components/PluginLinks.astro'; |
| 9 | +import Compatibility from '@components/plugins/Compatibility.astro'; |
| 10 | +import PluginPermissions from '@components/PluginPermissions.astro'; |
| 11 | +import { Tabs, TabItem, Steps } from '@astrojs/starlight/components'; |
| 12 | +import CommandTabs from '@components/CommandTabs.astro'; |
| 13 | + |
| 14 | +<PluginLinks plugin={frontmatter.plugin} /> |
| 15 | + |
| 16 | +Envía notificaciones nativas al usuario utilizando el plugin de notificaciones. |
| 17 | + |
| 18 | +## Plataformas soportadas |
| 19 | + |
| 20 | +<Compatibility plugin={frontmatter.plugin} /> |
| 21 | + |
| 22 | +## Configuración |
| 23 | + |
| 24 | +Instala el plugin de notificaciones para comenzar. |
| 25 | + |
| 26 | +<Tabs> |
| 27 | + <TabItem label="Automatic"> |
| 28 | + |
| 29 | + Utiliza el gestor de paquetes de tu proyecto para añadir la dependencia: |
| 30 | + |
| 31 | + <CommandTabs npm="npm run tauri add notification" |
| 32 | + yarn="yarn run tauri add notification" |
| 33 | + pnpm="pnpm tauri add notification" |
| 34 | + bun="bun tauri add notification" |
| 35 | + deno="deno task tauri add notification" |
| 36 | + cargo="cargo tauri add notification" /> |
| 37 | + |
| 38 | + |
| 39 | + </TabItem> |
| 40 | + <TabItem label="Manual"> |
| 41 | + <Steps> |
| 42 | + |
| 43 | + 1. Ejecuta el siguiente comando en el directorio `src-tauri` para añadir el plugin a las dependencias del proyecto en `Cargo.toml`: |
| 44 | + |
| 45 | + ```sh frame=none |
| 46 | + cargo add tauri-plugin-notification |
| 47 | + ``` |
| 48 | + |
| 49 | + 2. Modifica `lib.rs` para inicializar el plugin: |
| 50 | + |
| 51 | + ```rust title="src-tauri/src/lib.rs" ins={4} |
| 52 | + #[cfg_attr(mobile, tauri::mobile_entry_point)] |
| 53 | + pub fn run() { |
| 54 | + tauri::Builder::default() |
| 55 | + .plugin(tauri_plugin_notification::init()) |
| 56 | + .run(tauri::generate_context!()) |
| 57 | + .expect("error while running tauri application"); |
| 58 | + } |
| 59 | + ``` |
| 60 | + |
| 61 | + 3. Si deseas utilizar notificaciones desde JavaScript, instala también el paquete npm: |
| 62 | + |
| 63 | + |
| 64 | + <CommandTabs |
| 65 | + npm="npm install @tauri-apps/plugin-notification" |
| 66 | + yarn="yarn add @tauri-apps/plugin-notification" |
| 67 | + pnpm="pnpm add @tauri-apps/plugin-notification" |
| 68 | + deno="bun add npm:@tauri-apps/plugin-notification" |
| 69 | + bun="bun add @tauri-apps/plugin-notification" |
| 70 | + /> |
| 71 | + |
| 72 | + </Steps> |
| 73 | + </TabItem> |
| 74 | + |
| 75 | +</Tabs> |
| 76 | + |
| 77 | +## Uso |
| 78 | + |
| 79 | +Aquí hay algunos ejemplos de cómo usar el plugin de notificaciones: |
| 80 | + |
| 81 | +- [Enviar notificaciones a los usuarios](#enviar-notificación) |
| 82 | +- [Añadir una acción a una notificación](#actions) |
| 83 | +- [Añadir un adjunto a una notificación](#adjuntos) |
| 84 | +- [Enviar una notificación a un canal específico](#canales) |
| 85 | + |
| 86 | +El plugin de notificaciones está disponible tanto en JavaScript como en Rust. |
| 87 | + |
| 88 | +### Enviar notificación |
| 89 | + |
| 90 | +Sigue estos pasos para enviar una notificación: |
| 91 | + |
| 92 | +<Steps> |
| 93 | +1. Comprueba si se ha concedido el permiso |
| 94 | + |
| 95 | +2. Solicita permiso si no se ha concedido |
| 96 | + |
| 97 | +3. Envía la notificación |
| 98 | + |
| 99 | +</Steps> |
| 100 | + |
| 101 | +<Tabs syncKey="lang"> |
| 102 | +<TabItem label="JavaScript"> |
| 103 | + |
| 104 | +```javascript |
| 105 | +import { |
| 106 | + isPermissionGranted, |
| 107 | + requestPermission, |
| 108 | + sendNotification, |
| 109 | +} from '@tauri-apps/plugin-notification'; |
| 110 | +// si se usa `"withGlobalTauri": true`, puedes hacer |
| 111 | +// const { isPermissionGranted, requestPermission, sendNotification, } = window.__TAURI__.notification; |
| 112 | + |
| 113 | +// Tienes permiso para enviar una notificación? |
| 114 | +let permissionGranted = await isPermissionGranted(); |
| 115 | + |
| 116 | +// Si no es así, necesitamos solicitarlo |
| 117 | +if (!permissionGranted) { |
| 118 | + const permission = await requestPermission(); |
| 119 | + permissionGranted = permission === 'granted'; |
| 120 | +} |
| 121 | + |
| 122 | +// Una vez que se concede el permiso, envía la notificación |
| 123 | +if (permissionGranted) { |
| 124 | + sendNotification({ title: 'Tauri', body: 'Tauri is awesome!' }); |
| 125 | +} |
| 126 | +``` |
| 127 | + |
| 128 | +</TabItem> |
| 129 | +<TabItem label="Rust"> |
| 130 | + |
| 131 | +```rust |
| 132 | +tauri::Builder::default() |
| 133 | + .plugin(tauri_plugin_notification::init()) |
| 134 | + .setup(|app| { |
| 135 | + use tauri_plugin_notification::NotificationExt; |
| 136 | + app.notification() |
| 137 | + .builder() |
| 138 | + .title("Tauri") |
| 139 | + .body("Tauri es genial") |
| 140 | + .show() |
| 141 | + .unwrap(); |
| 142 | + |
| 143 | + Ok(()) |
| 144 | + }) |
| 145 | + .run(tauri::generate_context!()) |
| 146 | + .expect("error mientras se ejecutaba la aplicación tauri"); |
| 147 | +``` |
| 148 | + |
| 149 | +</TabItem> |
| 150 | +</Tabs> |
| 151 | + |
| 152 | +### Actions |
| 153 | + |
| 154 | +:::caution[Mobile Only] |
| 155 | +La API de Actions solo está disponible en plataformas móviles. |
| 156 | +::: |
| 157 | + |
| 158 | +Las acciones añaden botones e inputs interactivos a las notificaciones. Úsalas para crear una experiencia interactiva para tus usuarios. |
| 159 | + |
| 160 | +#### Registrar tipos de acciones |
| 161 | + |
| 162 | +Registra tipos de acciones para definir elementos interactivos: |
| 163 | + |
| 164 | +```javascript |
| 165 | +import { registerActionTypes } from '@tauri-apps/plugin-notification'; |
| 166 | + |
| 167 | +await registerActionTypes([ |
| 168 | + { |
| 169 | + id: 'messages', |
| 170 | + actions: [ |
| 171 | + { |
| 172 | + id: 'reply', |
| 173 | + title: 'Responder', |
| 174 | + input: true, |
| 175 | + inputButtonTitle: 'Enviar', |
| 176 | + inputPlaceholder: 'Escribe tu respuesta...', |
| 177 | + }, |
| 178 | + { |
| 179 | + id: 'mark-read', |
| 180 | + title: 'Marcar como leído', |
| 181 | + foreground: false, |
| 182 | + }, |
| 183 | + ], |
| 184 | + }, |
| 185 | +]); |
| 186 | +``` |
| 187 | + |
| 188 | +#### Propiedades de las acciones |
| 189 | + |
| 190 | +| Propiedad | Descripción | |
| 191 | +| ------------------------ | ------------------------------------------------------ | |
| 192 | +| `id` | Identificador único de la acción | |
| 193 | +| `title` | Texto a mostrar en la acción del botón | |
| 194 | +| `requiresAuthentication` | Requiere autenticación en el dispositivo | |
| 195 | +| `foreground` | Pone la aplicación en primer plano cuando es accionada | |
| 196 | +| `destructive` | Muestra la acción en rojo en iOS | |
| 197 | +| `input` | Habilita el campo de texto | |
| 198 | +| `inputButtonTitle` | Texto para el botón para enviar el input | |
| 199 | +| `inputPlaceholder` | Texto de ejemplo en el campo de texto | |
| 200 | + |
| 201 | +#### Suscribirse a acciones |
| 202 | + |
| 203 | +Suscribirse a notificaciones con acciones: |
| 204 | + |
| 205 | +```javascript |
| 206 | +import { onAction } from '@tauri-apps/plugin-notification'; |
| 207 | + |
| 208 | +await onAction((notification) => { |
| 209 | + console.log('Acción realizada:', notification); |
| 210 | +}); |
| 211 | +``` |
| 212 | + |
| 213 | +### Adjuntos |
| 214 | + |
| 215 | +Los adjuntos añaden contenido multimedia a las notificaciones. El soporte varía según la plataforma. |
| 216 | + |
| 217 | +```javascript |
| 218 | +import { sendNotification } from '@tauri-apps/plugin-notification'; |
| 219 | + |
| 220 | +sendNotification({ |
| 221 | + title: 'Nueva imagen', |
| 222 | + body: 'Mira esta imagen', |
| 223 | + attachments: [ |
| 224 | + { |
| 225 | + id: 'image-1', |
| 226 | + url: 'asset:///notification-image.jpg', |
| 227 | + }, |
| 228 | + ], |
| 229 | +}); |
| 230 | +``` |
| 231 | + |
| 232 | +#### Propiedades de los adjuntos |
| 233 | + |
| 234 | +| Propiedad | Descripción | |
| 235 | +| --------- | ---------------------------------------------------------- | |
| 236 | +| `id` | Identificador único | |
| 237 | +| `url` | URL del contenido usando los protocolos asset:// o file:// | |
| 238 | + |
| 239 | +Nota: Prueba los adjuntos en tus plataformas que quieras soportar para asegurarte de su compatibilidad. |
| 240 | + |
| 241 | +### Canales |
| 242 | + |
| 243 | +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. |
| 244 | + |
| 245 | +#### Crear un canal |
| 246 | + |
| 247 | +```javascript |
| 248 | +import { |
| 249 | + createChannel, |
| 250 | + Importance, |
| 251 | + Visibility, |
| 252 | +} from '@tauri-apps/plugin-notification'; |
| 253 | + |
| 254 | +await createChannel({ |
| 255 | + id: 'messages', |
| 256 | + name: 'Mensajes', |
| 257 | + description: 'Notificaciones para nuevos mensajes', |
| 258 | + importance: Importance.High, |
| 259 | + visibility: Visibility.Private, |
| 260 | + lights: true, |
| 261 | + lightColor: '#ff0000', |
| 262 | + vibration: true, |
| 263 | + sound: 'notification_sound', |
| 264 | +}); |
| 265 | +``` |
| 266 | + |
| 267 | +#### Propiedades de los canales |
| 268 | + |
| 269 | +| Propiedad | Descripción | |
| 270 | +| ------------- | -------------------------------------------------- | |
| 271 | +| `id` | Identificador único | |
| 272 | +| `name` | Nombre a mostrar | |
| 273 | +| `description` | Propósito del canal | |
| 274 | +| `importance` | Nivel de prioridad (None, Min, Low, Default, High) | |
| 275 | +| `visibility` | Nivel de privacidad (Secret, Private, Public) | |
| 276 | +| `lights` | Habilitar indicador LED (Android) | |
| 277 | +| `lightColor` | Color del indicador LED (Android) | |
| 278 | +| `vibration` | Habilitar vibraciones | |
| 279 | +| `sound` | Nombre del fichero para sonido personalizado | |
| 280 | + |
| 281 | +#### Gestionar canales |
| 282 | + |
| 283 | +Listar canales existentes: |
| 284 | + |
| 285 | +```javascript |
| 286 | +import { channels } from '@tauri-apps/plugin-notification'; |
| 287 | + |
| 288 | +const existingChannels = await channels(); |
| 289 | +``` |
| 290 | + |
| 291 | +Eliminar un canal: |
| 292 | + |
| 293 | +```javascript |
| 294 | +import { removeChannel } from '@tauri-apps/plugin-notification'; |
| 295 | + |
| 296 | +await removeChannel('messages'); |
| 297 | +``` |
| 298 | + |
| 299 | +#### Usando canales |
| 300 | + |
| 301 | +Enviar una notificación usando un canal: |
| 302 | + |
| 303 | +```javascript |
| 304 | +import { sendNotification } from '@tauri-apps/plugin-notification'; |
| 305 | + |
| 306 | +sendNotification({ |
| 307 | + title: 'Nuevo mensaje', |
| 308 | + body: 'Tienes un nuevo mensaje', |
| 309 | + channelId: 'messages', |
| 310 | +}); |
| 311 | +``` |
| 312 | + |
| 313 | +Nota: Crea canales antes de enviar notificaciones que los referencien. Los identificadores de canal inválidos impiden que las notificaciones se muestren. |
| 314 | + |
| 315 | +## Consideraciones de seguridad |
| 316 | + |
| 317 | +Aparte de los procedimientos normales de sanitización de la entrada del usuario, actualmente no hay consideraciones de seguridad conocidas. |
| 318 | + |
| 319 | +<PluginPermissions plugin={frontmatter.plugin} /> |
0 commit comments