乐闻世界logo
搜索文章和话题

Tauri 提供哪些常用的系统 API

2月19日 19:25

Tauri 提供了丰富的 API 来访问系统功能,主要包括以下模块:

文件系统 API

typescript
import { readTextFile, writeTextFile, exists } from '@tauri-apps/api/fs'; // 读取文件 const content = await readTextFile('path/to/file.txt'); // 写入文件 await writeTextFile('path/to/file.txt', 'Hello World'); // 检查文件是否存在 const fileExists = await exists('path/to/file.txt');

Shell API

typescript
import { open } from '@tauri-apps/api/shell'; // 打开外部链接 await open('https://example.com'); // 执行命令 const { stdout } = await Command.create('ls', ['-l']).execute();

对话框 API

typescript
import { open, save } from '@tauri-apps/api/dialog'; // 打开文件选择器 const selected = await open({ multiple: true, filters: [{ name: 'Images', extensions: ['png', 'jpg', 'jpeg'] }] }); // 保存文件对话框 const filePath = await save({ defaultPath: 'document.txt', filters: [{ name: 'Text', extensions: ['txt'] }] });

窗口 API

typescript
import { appWindow } from '@tauri-apps/api/window'; // 获取窗口信息 const label = appWindow.label; const scaleFactor = await appWindow.scaleFactor(); // 窗口控制 await appWindow.minimize(); await appWindow.maximize(); await appWindow.close(); // 监听窗口事件 const unlisten = await appWindow.onResized(({ payload }) => { console.log('Window resized:', payload); });

通知 API

typescript
import { sendNotification } from '@tauri-apps/api/notification'; sendNotification({ title: 'Notification', body: 'This is a notification' });

剪贴板 API

typescript
import { readText, writeText } from '@tauri-apps/api/clipboard'; // 读取剪贴板 const text = await readText(); // 写入剪贴板 await writeText('Hello World');

全局快捷键 API

typescript
import { register, unregisterAll } from '@tauri-apps/api/globalShortcut'; // 注册快捷键 await register('CommandOrControl+Shift+1', () => { console.log('Shortcut pressed'); }); // 注销所有快捷键 await unregisterAll();

权限配置

tauri.conf.json 中声明所需权限:

json
{ "tauri": { "allowlist": { "fs": { "all": true }, "shell": { "all": true }, "dialog": { "all": true }, "window": { "all": true }, "notification": { "all": true }, "clipboard": { "all": true }, "globalShortcut": { "all": true } } } }
标签:Tauri