0
# Core IPC & Plugins
1
2
The core module provides the foundation for all communication between the frontend and Rust backend in Tauri applications. It handles command invocation, plugin management, resource lifecycle, and IPC serialization.
3
4
## Capabilities
5
6
### Command Invocation
7
8
Execute Rust commands from the frontend with typed parameters and return values.
9
10
```typescript { .api }
11
/**
12
* Invoke a Rust command from the frontend
13
* @param cmd - Command name registered in Rust
14
* @param args - Arguments to pass to the command
15
* @param options - Optional headers for the request
16
* @returns Promise resolving to command result
17
*/
18
function invoke<T>(cmd: string, args?: InvokeArgs, options?: InvokeOptions): Promise<T>;
19
20
type InvokeArgs = Record<string, unknown> | number[] | ArrayBuffer | Uint8Array;
21
22
interface InvokeOptions {
23
headers: HeadersInit;
24
}
25
```
26
27
**Usage Examples:**
28
29
```typescript
30
import { invoke } from '@tauri-apps/api/core';
31
32
// Simple command with no parameters
33
const version = await invoke<string>('get_app_version');
34
35
// Command with object parameters
36
const result = await invoke<UserData>('create_user', {
37
name: 'John Doe',
38
email: 'john@example.com'
39
});
40
41
// Command with binary data
42
const imageData = new Uint8Array([/* image bytes */]);
43
const processed = await invoke<Uint8Array>('process_image', imageData);
44
45
// Command with custom headers
46
const data = await invoke<string>('authenticated_request',
47
{ query: 'SELECT * FROM users' },
48
{ headers: { 'Authorization': 'Bearer token123' } }
49
);
50
```
51
52
### Environment Detection
53
54
Check if the code is running in a Tauri environment.
55
56
```typescript { .api }
57
/**
58
* Check if the current environment is a Tauri application
59
* @returns true if running in Tauri, false otherwise
60
*/
61
function isTauri(): boolean;
62
```
63
64
**Usage Example:**
65
66
```typescript
67
import { isTauri } from '@tauri-apps/api/core';
68
69
if (isTauri()) {
70
// Use Tauri-specific APIs
71
const window = await getCurrentWindow();
72
} else {
73
// Fallback for web environment
74
console.log('Running in browser');
75
}
76
```
77
78
### File URL Conversion
79
80
Convert local file paths to URLs that can be used in the frontend.
81
82
```typescript { .api }
83
/**
84
* Convert a file path to an asset URL that can be loaded by the frontend
85
* @param filePath - Local file path
86
* @param protocol - Optional protocol to use (defaults to 'asset')
87
* @returns URL string that can be used in img src, etc.
88
*/
89
function convertFileSrc(filePath: string, protocol?: string): string;
90
```
91
92
**Usage Example:**
93
94
```typescript
95
import { convertFileSrc } from '@tauri-apps/api/core';
96
97
// Convert local file to usable URL
98
const imagePath = '/path/to/local/image.png';
99
const imageUrl = convertFileSrc(imagePath);
100
101
// Use in HTML
102
const img = document.createElement('img');
103
img.src = imageUrl; // Will be something like 'asset://localhost/path/to/local/image.png'
104
105
// With custom protocol
106
const customUrl = convertFileSrc(imagePath, 'myprotocol');
107
```
108
109
### IPC Channels
110
111
Bidirectional communication channels for streaming data between frontend and backend.
112
113
```typescript { .api }
114
/**
115
* Bidirectional IPC communication channel with message ordering
116
*/
117
class Channel<T> {
118
/**
119
* Create a new IPC channel
120
* @param onmessage - Optional callback for incoming messages
121
*/
122
constructor(onmessage?: (response: T) => void);
123
124
/**
125
* Channel identifier returned from transformCallback
126
*/
127
readonly id: number;
128
129
/**
130
* Message handler that can be updated
131
*/
132
onmessage: (response: T) => void;
133
}
134
```
135
136
**Usage Example:**
137
138
```typescript
139
import { Channel } from '@tauri-apps/api/core';
140
141
// Create a channel for real-time data
142
const dataChannel = new Channel<{ type: string; data: any }>((message) => {
143
console.log('Received:', message);
144
});
145
146
// The channel is used by passing its ID to Rust backend commands
147
// The backend can send messages to this channel using the ID
148
console.log('Channel ID:', dataChannel.id);
149
150
// Update the message handler
151
dataChannel.onmessage = (message) => {
152
console.log('Updated handler received:', message);
153
};
154
```
155
156
### Plugin System
157
158
Manage Tauri plugins and their permissions.
159
160
```typescript { .api }
161
/**
162
* Add a listener for plugin events
163
* @param plugin - Plugin identifier
164
* @param event - Event name to listen for
165
* @param cb - Callback function for handling events
166
* @returns Promise resolving to listener handle
167
*/
168
function addPluginListener<T>(
169
plugin: string,
170
event: string,
171
cb: (payload: T) => void
172
): Promise<PluginListener>;
173
174
/**
175
* Check current permissions for a plugin
176
* @param plugin - Plugin identifier
177
* @returns Promise resolving to current permission state
178
*/
179
function checkPermissions<T>(plugin: string): Promise<T>;
180
181
/**
182
* Request permissions for a plugin
183
* @param plugin - Plugin identifier
184
* @returns Promise resolving to granted permission state
185
*/
186
function requestPermissions<T>(plugin: string): Promise<T>;
187
188
/**
189
* Plugin event listener handle
190
*/
191
class PluginListener {
192
/**
193
* Remove the event listener
194
*/
195
unregister(): Promise<void>;
196
}
197
198
type PermissionState = 'granted' | 'denied' | 'prompt' | 'prompt-with-rationale';
199
```
200
201
**Usage Examples:**
202
203
```typescript
204
import { addPluginListener, checkPermissions, requestPermissions } from '@tauri-apps/api/core';
205
206
// Listen for plugin events
207
const listener = await addPluginListener('notifications', 'received', (payload) => {
208
console.log('Notification received:', payload);
209
});
210
211
// Check permissions
212
const currentPerms = await checkPermissions('camera');
213
if (currentPerms.camera !== 'granted') {
214
// Request permissions
215
const newPerms = await requestPermissions('camera');
216
console.log('Camera permission:', newPerms.camera);
217
}
218
219
// Clean up listener
220
await listener.unregister();
221
```
222
223
### Resource Management
224
225
Base class for managing Rust-backed resources with automatic cleanup.
226
227
```typescript { .api }
228
/**
229
* Base class for Rust-backed resources that need cleanup
230
*/
231
class Resource {
232
/**
233
* Create a resource with the given Rust resource ID
234
* @param rid - Resource identifier from Rust
235
*/
236
constructor(rid: number);
237
238
/**
239
* Close the resource and free associated memory
240
*/
241
close(): Promise<void>;
242
}
243
```
244
245
**Usage Example:**
246
247
```typescript
248
import { Resource } from '@tauri-apps/api/core';
249
250
class MyCustomResource extends Resource {
251
async doSomething() {
252
// Resource operations here
253
}
254
255
async cleanup() {
256
await this.close(); // Clean up Rust resource
257
}
258
}
259
```
260
261
### Custom IPC Serialization
262
263
Define custom serialization for complex objects passed through IPC.
264
265
```typescript { .api }
266
/**
267
* Symbol key for implementing custom IPC serialization
268
*/
269
const SERIALIZE_TO_IPC_FN: string;
270
```
271
272
**Usage Example:**
273
274
```typescript
275
import { SERIALIZE_TO_IPC_FN } from '@tauri-apps/api/core';
276
277
// Custom class with IPC serialization
278
class UserId {
279
constructor(private id: string) {}
280
281
// Custom serialization for IPC
282
[SERIALIZE_TO_IPC_FN]() {
283
return { String: this.id };
284
}
285
}
286
287
// Usage with invoke
288
const userId = new UserId('user123');
289
const result = await invoke('process_user', { userId });
290
```
291
292
### Callback Management
293
294
Low-level callback transformation for IPC communication.
295
296
```typescript { .api }
297
/**
298
* Transform a callback function for IPC communication
299
* @param callback - Callback function to transform
300
* @param once - Whether callback should only be called once
301
* @returns Callback ID for IPC
302
*/
303
function transformCallback<T>(
304
callback?: (response: T) => void,
305
once?: boolean
306
): number;
307
```
308
309
**Note:** This is typically used internally by other Tauri APIs and rarely needed in application code.
310
311
## Error Handling
312
313
IPC operations can fail for various reasons:
314
315
```typescript
316
import { invoke } from '@tauri-apps/api/core';
317
318
try {
319
const result = await invoke('my_command', { data: 'test' });
320
console.log('Success:', result);
321
} catch (error) {
322
// Common error types:
323
// - Command not found
324
// - Invalid arguments
325
// - Backend error
326
// - Permission denied
327
console.error('IPC error:', error);
328
}
329
```
330
331
## Performance Considerations
332
333
- Use `Channel` for streaming/real-time data instead of repeated `invoke` calls
334
- Batch multiple operations when possible to reduce IPC overhead
335
- Consider using binary data types (`Uint8Array`, `ArrayBuffer`) for large payloads
336
- Implement proper resource cleanup with `Resource.close()` to prevent memory leaks