Tauri's IPC (Inter-Process Communication) mechanism is the core for communication between the frontend and Rust backend, primarily implemented through the following methods:
Frontend Calling Rust Backend
Use the invoke method from @tauri-apps/api/tauri:
typescriptimport { invoke } from '@tauri-apps/api/tauri'; // Call Rust command const result = await invoke('greet', { name: 'World' });
Defining Commands in Rust
Use the #[tauri::command] macro in src-tauri/src/main.rs:
rust#[tauri::command] fn greet(name: &str) -> String { format!("Hello, {}!", name) } fn main() { tauri::Builder::default() .invoke_handler(tauri::generate_handler![greet]) .run(tauri::generate_context!()) .expect("error while running tauri application"); }
Rust Backend Actively Pushing Messages to Frontend
Use the emit method:
rust// Rust side window.emit("event-name", payload)?; // Frontend listening import { listen } from '@tauri-apps/api/event'; const unlisten = await listen('event-name', (event) => { console.log(event.payload); });
Data Serialization
- Automatically uses JSON for serialization and deserialization
- Supports complex data types (objects, arrays, etc.)
- Rust side needs to implement
SerializeandDeserializetraits
Error Handling
- Rust side returning
Resulttype is automatically converted to Promise - Frontend can use try-catch to catch errors