使用插件权限
本练习的目标是更好地理解如何启用或禁用插件权限,它们在哪里被描述,以及如何使用插件的默认权限。
🌐 The goal of this exercise is to get a better understanding on how plugin permissions can be enabled or disabled, where they are described and how to use default permissions of plugins.
到最后,你将具备查找和使用任意插件权限的能力,并且能够理解如何定制现有权限。你将拥有一个示例 Tauri 应用,其中使用了一个插件及其特定权限。
🌐 At the end you will have the ability to find and use permissions of arbitrary plugins and understand how to custom tailor existing permissions. You will have an example Tauri application where a plugin and plugin specific permissions are used.
-
创建你的 Tauri 应用。 在我们的示例中,我们将实现
create-tauri-app:sh <(curl https://create.tauri.app/sh)irm https://create.tauri.app/ps | iexsh (curl -sSL https://create.tauri.app/sh | psub)npm create tauri-app@latestyarn create tauri-apppnpm create tauri-appdeno run -A npm:create-tauri-appbun create tauri-appcargo install create-tauri-app --lockedcargo create-tauri-app我们将在这个逐步解释中使用
pnpm,但你可以选择其他包管理器并相应地在命令中替换它。pnpm create tauri-app✔ Project name · plugin-permission-demo✔ Choose which language to use for your frontend · TypeScript / JavaScript - (pnpm, yarn, npm, bun)✔ Choose your package manager · pnpm✔ Choose your UI template · Vanilla✔ Choose your UI flavor · TypeScriptTemplate created! To get started run:cd plugin-permission-demopnpm installpnpm tauri dev -
要搜索现有的插件,你可以使用多种资源。
最直接的方法是查看你的插件是否已经在文档的 插件 部分中,因此成为 Tauri 维护的插件集合的一部分。Filesystem 插件是 Tauri 插件工作区的一部分,你可以按照 说明 将其添加到你的项目中。
如果该插件是社区努力的一部分,你很可能可以在 crates.io 上通过搜索
tauri-plugin-<your plugin name>找到它。如果它是我们工作区现有的插件,你可以使用自动化方式:
pnpm tauri add fs如果你在 crates.io 上找到了它,你需要手动将其作为依赖添加,并修改 Tauri 构建器以初始化插件:
Terminal window cargo add tauri-plugin-fs修改
lib.rs以初始化插件:src-tauri/src/lib.rs #[cfg_attr(mobile, tauri::mobile_entry_point)]fn run() {tauri::Builder::default().plugin(tauri_plugin_fs::init()).run(tauri::generate_context!()).expect("error while running tauri application");} -
每个插件都有一个
default权限集,其中包含所有权限和范围,可在开箱即可用的合理最小功能集下使用该插件。对于官方维护的插件,你可以在文档中找到已渲染的描述(例如 fs default)。
如果你是为一个社区插件搞清楚这个问题,你需要查看该插件的源代码。这应该在
your-plugin/permissions/default.toml中定义。"$schema" = "schemas/schema.json"[default]description = """# Tauri `fs` default permissionsThis configuration file defines the default permissions grantedto the filesystem.### Granted PermissionsThis default permission set enables all read-related commands andallows access to the `$APP` folder and sub directories created in it.The location of the `$APP` folder depends on the operating system,where the application is run.In general the `$APP` folder needs to be manually createdby the application at runtime, before accessing files or foldersin it is possible.### Denied PermissionsThis default permission set prevents access to critical componentsof the Tauri application by default.On Windows the webview data folder access is denied."""permissions = ["read-all", "scope-app-recursive", "deny-default"] -
这一步完全是关于找到你需要的权限,以使你的命令能够以对系统访问最小化的方式暴露给前端。
fs插件已自动生成权限,这将禁用或启用单个命令,并允许或禁用全局范围。这些可以在文档中找到,或者在插件的源代码(
fs/permissions/autogenerated)中找到。假设我们想要启用对位于用户
$HOME文件夹中的文本文件test.txt的写入。为此,我们将在自动生成的权限中搜索一个允许写入文本文件如
allow-write-text-file的权限,然后再搜索一个允许我们访问$HOME/test.txt文件的范围。我们需要将这些添加到我们
src-tauri/tauri.conf.json的capabilities部分,或者添加到src-tauri/capabilities/文件夹中的文件中。默认情况下,src-tauri/capabilities/default.json已经有一个可以修改的功能。src-tauri/capabilities/default.json {"$schema": "../gen/schemas/desktop-schema.json","identifier": "default","description": "Capability for the main window","windows": ["main"],"permissions": ["path:default","event:default","window:default","app:default","image:default","resources:default","menu:default","tray:default","shell:allow-open","fs:default","fs:allow-write-text-file",]}由于
fs插件中只有自动生成的作用域来访问整个$HOME文件夹,我们需要配置自己的作用域。这个作用域应该仅在write-text-file命令下启用,并且只应暴露我们的test.txt文件。src-tauri/capabilities/default.json {"$schema": "../gen/schemas/desktop-schema.json","identifier": "default","description": "Capability for the main window","windows": ["main"],"permissions": ["path:default","event:default","window:default","app:default","image:default","resources:default","menu:default","tray:default","shell:allow-open","fs:allow-write-text-file",{"identifier": "fs:allow-write-text-file","allow": [{ "path": "$HOME/test.txt" }]},]} -
在我们添加了必要的权限之后,我们想确认我们的应用可以访问该文件并写入它的内容。
我们可以在我们的应用中使用这个代码片段来写入文件:
src/main.ts import { writeTextFile, BaseDirectory } from '@tauri-apps/plugin-fs';let greetInputEl: HTMLInputElement | null;async function write(message: string) {await writeTextFile('test.txt', message, { baseDir: BaseDirectory.Home });}window.addEventListener("DOMContentLoaded", () => {greetInputEl = document.querySelector("#greet-input");document.querySelector("#greet-form")?.addEventListener("submit", (e) => {e.preventDefault();if (!greetInputEl )return;write(greetInputEl.value == "" ? "No input provided": greetInputEl.value);});});将
src/main.ts替换为此代码片段意味着在使用标准 Vanilla+Typescript 应用时,我们无需修改默认的index.html。 在运行的应用的输入字段中输入任何内容都会在提交时写入文件。现在让我们实际测试一下:
pnpm run tauri dev在输入内容并点击“提交”后,我们可以通过终端模拟器检查,或者通过手动打开你主目录下的文件来查看。
cat $HOME/test.txt你应该会看到你的输入,并完成关于在 Tauri 应用中使用插件权限的学习。 🥳
如果你遇到此错误:
Terminal window [Error] Unhandled Promise Rejection: fs.write_text_file not allowed. Permissions associated with this command: fs:allow-app-write, fs:allow-app-write-recursive, fs:allow-appcache-write, fs:allow-appcache-write-recursive, fs:allow-appconf...(anonymous function) (main.ts:5)Then you very likely did not properly follow the previous instructions.
Tauri 中文网 - 粤ICP备13048890号
Nodejs.cn 旗下网站