Single Instance
Ensure that a single instance of your tauri app is running at a time using the Single Instance Plugin.
Setup
Install the Single Instance plugin to get started.
Use your project’s package manager to add the dependency:
npm run tauri add single-instance
yarn run tauri add single-instance
pnpm tauri add single-instance
bun tauri add single-instance
cargo tauri add single-instance
Install : Add the plugin to the project’s dependencies in
Cargo.toml
.src-tauri/Cargo.toml [dependencies]tauri-plugin-single-instance = "2.0.0-beta"src-tauri/Cargo.toml [dependencies]tauri-plugin-single-instance = { git = "https://github.com/tauri-apps/plugins-workspace", branch = "v2" }Initialize : Update
lib.rs
(ormain.rs
for desktop-only apps) to initialize the plugin:src-tauri/src/lib.rs pub fn run() {tauri::Builder::default().plugin(tauri_plugin_single_instance::init(|app, args, cwd| {})).run(tauri::generate_context!()).expect("error while running tauri application");}
Usage
The plugin is already installed and initialized, and it should be functioning correctly right away. Nevertheless, we can also enhance its functionality with the init()
method.
The plugin init()
method takes a closure that is invoked when a new app instance was started, but closed by the plugin.
The closure has three arguments:
app
: The AppHandle of the application.args
: The list of arguments, that was passed by the user to initiate this new instance.cwd
: The Current Working Directory denotes the directory from which the new application instance was launched.
So, the closure should look like below
.plugin(tauri_plugin_single_instance::init(|app, args, cwd| { // Write your code here...}))
Focusing on New Instance
By default, when you initiate a new instance while the application is already running, no action is taken. To focus the window of the running instance when user tries to open a new instance, alter the callback closure as follows:
use tauri::{AppHandle, Manager};
pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_single_instance::init(|app, args, cwd| { let _ = show_window(app); })) .run(tauri::generate_context!()) .expect("error while running tauri application");}
fn show_window(app: &AppHandle) { let windows = app.webview_windows();
windows .values() .next() .expect("Sorry, no window found") .set_focus() .expect("Can't Bring Window to Focus");}
© 2024 Tauri Contributors. CC-BY / MIT