撰寫外掛程式權限
本練習的目標是更好地理解在撰寫自己的外掛程式時,如何建立外掛程式權限。
最後,您將能夠為您的外掛程式建立簡單的權限。您將有一個 Tauri 外掛程式範例,其中權限是部分自動產生和手工製作的。
-
在我們的範例中,我們將使用 Tauri
cli
來引導 Tauri 外掛程式原始碼結構。請確保您已安裝所有先決條件,並執行cargo tauri info
來驗證您是否擁有正確版本的 Tauri CLI。輸出應指示
tauri-cli
版本為2.x
。我們將在逐步說明中繼續使用pnpm
,但您可以選擇其他套件管理器,並在指令中相應地替換它。一旦您安裝了最新版本,您就可以繼續使用 Tauri CLI 建立外掛程式。
終端機視窗 mkdir -p tauri-learningcd tauri-learningcargo tauri plugin new testcd tauri-plugin-testpnpm installpnpm buildcargo build -
為了展示一些實用且簡單的東西,讓我們假設我們的指令將使用者輸入寫入到我們暫存資料夾中的檔案,同時向檔案新增一些自訂標頭。
讓我們將我們的指令命名為
write_custom_file
,在src/commands.rs
中實作它,並將其新增到我們的外掛程式建構器中,以公開給前端。Tauri 的核心工具將為此指令自動產生
allow
和deny
權限,因此我們不需要關心這一點。指令實作
src/commands.rs use tauri::{AppHandle, command, Runtime};use crate::models::*;use crate::Result;use crate::TestExt;#[command]pub(crate) async fn ping<R: Runtime>(app: AppHandle<R>,payload: PingRequest,) -> Result<PingResponse> {app.test1().ping(payload)}#[command]pub(crate) async fn write_custom_file<R: Runtime>(user_input: String,app: AppHandle<R>,) -> Result<String> {std::fs::write(app.path().temp_dir().unwrap(), user_input)?;Ok("success".to_string())}為您的新指令自動產生內建權限
src/build.rs const COMMANDS: &[&str] = &["ping", "write_custom_file"];這些內建權限將由 Tauri 建置系統自動產生,並且將在
permissions/autogenerated/commands
資料夾中可見。預設情況下,將建立enable-<command>
和deny-<command>
權限。 -
先前的步驟是撰寫實際的指令實作。接下來,我們想要將其公開給前端,以便可以使用它。
設定 Tauri 建構器以產生調用處理程式,以將前端 IPC 請求傳遞到新實作的指令
src/lib.rs pub fn init<R: Runtime>() -> TauriPlugin<R> {Builder::new("test").invoke_handler(tauri::generate_handler![commands::ping,commands::write_custom_file,]).setup(|app, api| {#[cfg(mobile)]let test = mobile::init(app, api)?;#[cfg(desktop)]let test = desktop::init(app, api)?;app.manage(test);// manage state so it is accessible by the commandsapp.manage(MyState::default());Ok(())}).build()}在前模組中公開新指令。
此步驟對於範例應用程式成功匯入前模組至關重要。這僅是為了方便起見,並且沒有安全影響,因為指令處理程式已經產生,並且可以從前端手動調用指令。
guest-js/index.ts import { invoke } from '@tauri-apps/api/core'export async function ping(value: string): Promise<string | null> {return await invoke<{value?: string}>('plugin:test|ping', {payload: {value,},}).then((r) => (r.value ? r.value : null));}export async function writeCustomFile(user_input: string): Promise<string> {return await invoke('plugin:test|write_custom_file',{userInput: user_input});}確保您的套件已建置
pnpm build -
由於我們的外掛程式應預設公開
write_custom_file
指令,因此我們應將其新增到我們的default.toml
權限。將此新增到我們的預設權限集中,以允許我們剛公開的新指令。
permissions/default.toml "$schema" = "schemas/schema.json"[default]description = "Default permissions for the plugin"permissions = ["allow-ping", "allow-write-custom-file"] -
建立的外掛程式目錄結構包含一個
examples/tauri-app
資料夾,其中有一個可立即使用的 Tauri 應用程式來測試外掛程式。由於我們新增了一個新指令,因此我們需要稍微修改前端以調用我們的新指令。
src/App.svelte <script>import Greet from './lib/Greet.svelte'import { ping, writeCustomFile } from 'tauri-plugin-test-api'let response = ''function updateResponse(returnValue) {response += `[${new Date().toLocaleTimeString()}]` + (typeof returnValue === 'string' ? returnValue : JSON.stringify(returnValue)) + '<br>'}function _ping() {ping("Pong!").then(updateResponse).catch(updateResponse)}function _writeCustomFile() {writeCustomFile("HELLO FROM TAURI PLUGIN").then(updateResponse).catch(updateResponse)}</script><main class="container"><h1>Welcome to Tauri!</h1><div class="row"><a href="https://vite.dev.org.tw" target="_blank"><img src="/vite.svg" class="logo vite" alt="Vite Logo" /></a><a href="https://tauri.dev.org.tw" target="_blank"><img src="/tauri.svg" class="logo tauri" alt="Tauri Logo" /></a><a href="https://svelte.dev.org.tw" target="_blank"><img src="/svelte.svg" class="logo svelte" alt="Svelte Logo" /></a></div><p>Click on the Tauri, Vite, and Svelte logos to learn more.</p><div class="row"><Greet /></div><div><button on:click="{_ping}">Ping</button><div>{@html response}</div></div><div><button on:click="{_writeCustomFile}">Write</button><div>{@html response}</div></div></main><style>.logo.vite:hover {filter: drop-shadow(0 0 2em #747bff);}.logo.svelte:hover {filter: drop-shadow(0 0 2em #ff3e00);}</style>執行此操作並按下「寫入」按鈕,您應該會看到這個
success您應該在您的暫存資料夾中找到一個
test.txt
檔案,其中包含來自我們新實作的外掛程式指令的訊息。🥳
© 2025 Tauri Contributors. CC-BY / MIT