窗口状态
保存窗口位置和大小,并在应用重新打开时恢复它们。
支持的平台
此插件需要至少 1.77.2 版本的 Rust
平台 | 级别 | 备注 |
---|---|---|
windows | ||
linux | ||
macos | ||
android | | |
ios | |
设置
安装 window-state 插件以开始使用。
使用你的项目包管理器添加依赖项
npm run tauri add window-state
yarn run tauri add window-state
pnpm tauri add window-state
deno task tauri add window-state
bun tauri add window-state
cargo tauri add window-state
-
在
src-tauri
文件夹中运行以下命令,将插件添加到Cargo.toml
项目依赖项中cargo add tauri-plugin-window-state --target 'cfg(any(target_os = "macos", windows, target_os = "linux"))' -
修改
lib.rs
以初始化插件src-tauri/src/lib.rs #[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {tauri::Builder::default().setup(|app| {#[cfg(desktop)]app.handle().plugin(tauri_plugin_window_state::Builder::default().build());Ok(())}).run(tauri::generate_context!()).expect("error while running tauri application");} -
使用你喜欢的 JavaScript 包管理器安装 JavaScript Guest 绑定
npm install @tauri-apps/plugin-window-stateyarn add @tauri-apps/plugin-window-statepnpm add @tauri-apps/plugin-window-statedeno add npm:@tauri-apps/plugin-window-statebun add @tauri-apps/plugin-window-state
用法
添加 window-state 插件后,所有窗口将在应用关闭时记住其状态,并在下次启动时恢复到之前的状态。
你也可以在 JavaScript 和 Rust 中访问 window-state 插件。
JavaScript
你可以使用 saveWindowState
手动保存窗口状态
import { saveWindowState, StateFlags } from '@tauri-apps/plugin-window-state';// when using `"withGlobalTauri": true`, you may use// const { saveWindowState, StateFlags } = window.__TAURI__.windowState;
saveWindowState(StateFlags.ALL);
同样,你可以从磁盘手动恢复窗口状态
import { restoreStateCurrent, StateFlags,} from '@tauri-apps/plugin-window-state';// when using `"withGlobalTauri": true`, you may use// const { restoreStateCurrent, StateFlags } = window.__TAURI__.windowState;
restoreStateCurrent(StateFlags.ALL);
Rust
你可以使用 AppHandleExt
trait 公开的 save_window_state()
方法
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
// `tauri::AppHandle` now has the following additional methodapp.save_window_state(StateFlags::all()); // will save the state of all open windows to disk
同样,你可以使用 WindowExt
trait 公开的 restore_state()
方法从磁盘手动恢复窗口状态
use tauri_plugin_window_state::{WindowExt, StateFlags};
// all `Window` types now have the following additional methodwindow.restore_state(StateFlags::all()); // will restore the window's state from disk
权限
默认情况下,所有潜在危险的插件命令和作用域都被阻止且无法访问。你必须修改 capabilities
配置中的权限才能启用它们。
有关更多信息,请参阅 Capabilities Overview,以及使用插件权限的 step by step guide。
{ "permissions": [ ..., "window-state:default", ]}
默认权限
此权限集配置了 window state 插件可用的操作类型。
授予的权限
默认情况下,所有操作都已启用。
此默认权限集包括以下内容
allow-filename
allow-restore-state
allow-save-window-state
权限表
标识符 | 描述 |
---|---|
|
启用 filename 命令,无需任何预配置的作用域。 |
|
拒绝 filename 命令,无需任何预配置的作用域。 |
|
启用 restore_state 命令,无需任何预配置的作用域。 |
|
拒绝 restore_state 命令,无需任何预配置的作用域。 |
|
启用 save_window_state 命令,无需任何预配置的作用域。 |
|
拒绝 save_window_state 命令,无需任何预配置的作用域。 |
© 2025 Tauri 贡献者。CC-BY / MIT