### Start Development Server with Bun Source: https://v2.tauri.app/start/create-project Navigate to the project directory, install dependencies, and start the Tauri development server using Bun. ```bun cd tauri-app bun install bun tauri dev ``` -------------------------------- ### Add content to pre-install script Source: https://v2.tauri.app/distribute/rpm Example content for a `preinstall.sh` script, demonstrating how to print messages and access installation values. ```bash echo "-------------" echo "This is pre" echo "Install Value: $1" echo "Upgrade Value: $1" echo "Uninstall Value: $1" echo "-------------" ``` -------------------------------- ### Start Development Server with npm Source: https://v2.tauri.app/start/create-project Navigate to the project directory, install dependencies, and start the Tauri development server using npm. ```npm cd tauri-app npm install npm run tauri dev ``` -------------------------------- ### Add content to post-install script Source: https://v2.tauri.app/distribute/rpm Example content for a `postinstall.sh` script, demonstrating how to print messages and access installation values. ```bash echo "-------------" echo "This is post" echo "Install Value: $1" echo "Upgrade Value: $1" echo "Uninstall Value: $1" echo "-------------" ``` -------------------------------- ### Start Development Server with Deno Source: https://v2.tauri.app/start/create-project Navigate to the project directory, install dependencies, and start the Tauri development server using Deno. ```deno cd tauri-app deno install deno task tauri dev ``` -------------------------------- ### Start Development Server with Yarn Source: https://v2.tauri.app/start/create-project Navigate to the project directory, install dependencies, and start the Tauri development server using Yarn. ```yarn cd tauri-app yarn install yarn tauri dev ``` -------------------------------- ### Start Development Server with Cargo Source: https://v2.tauri.app/start/create-project Navigate to the project directory, install the Tauri CLI, and start the development server using Cargo. ```rust cd tauri-app cargo install tauri-cli --version "^2.0.0" --locked cargo tauri dev ``` -------------------------------- ### Start Development Server with pnpm Source: https://v2.tauri.app/start/create-project Navigate to the project directory, install dependencies, and start the Tauri development server using pnpm. ```pnpm cd tauri-app pnpm install pnpm tauri dev ``` -------------------------------- ### JavaScript: Get or Load a Store Instance Source: https://v2.tauri.app/reference/javascript/store This example demonstrates how to retrieve an existing store using `Store.get()` or load it if it hasn't been initialized yet. ```javascript import { Store } from '@tauri-apps/api/store'; let store = await Store.get('store.json'); if (!store) { store = await Store.load('store.json'); } ``` -------------------------------- ### Check and Install Updates in Rust Source: https://v2.tauri.app/plugin/updater This example shows how to integrate the updater plugin into a Tauri application's setup function. It checks for updates, monitors download progress, and restarts the application upon successful installation. ```rust use tauri_plugin_updater::UpdaterExt; pub fn run() { tauri::Builder::default() .setup(|app| { let handle = app.handle().clone(); tauri::async_runtime::spawn(async move { update(handle).await.unwrap(); }); Ok(()) }) .run(tauri::generate_context!()) .unwrap(); } async fn update(app: tauri::AppHandle) -> tauri_plugin_updater::Result<()> { if let Some(update) = app.updater()?.check().await? { let mut downloaded = 0; // alternatively we could also call update.download() and update.install() separately update .download_and_install( |chunk_length, content_length| { downloaded += chunk_length; println!("downloaded {downloaded} from {content_length:?}"); }, || { println!("download finished"); }, ) .await?; println!("update installed"); app.restart(); } Ok(()) } ``` -------------------------------- ### Install JavaScript Guest Bindings with Deno Source: https://v2.tauri.app/plugin/window-state Install the JavaScript guest bindings for the window-state plugin using Deno. ```bash deno add npm:@tauri-apps/plugin-window-state ``` -------------------------------- ### Install JavaScript Guest Bindings with npm Source: https://v2.tauri.app/plugin/window-state Install the JavaScript guest bindings for the window-state plugin using npm. ```bash npm install @tauri-apps/plugin-window-state ``` -------------------------------- ### Install JavaScript Guest Bindings with Bun Source: https://v2.tauri.app/plugin/window-state Install the JavaScript guest bindings for the window-state plugin using Bun. ```bash bun add @tauri-apps/plugin-window-state ``` -------------------------------- ### Install Snapcraft CLI Source: https://v2.tauri.app/distribute/snapcraft Install the snapcraft command-line tool with classic confinement to build snap packages. ```bash sudo snap install snapcraft --classic ``` -------------------------------- ### Install JavaScript Guest Bindings with yarn Source: https://v2.tauri.app/plugin/window-state Install the JavaScript guest bindings for the window-state plugin using yarn. ```bash yarn add @tauri-apps/plugin-window-state ``` -------------------------------- ### Get Current OS Version (JavaScript) Source: https://v2.tauri.app/reference/javascript/os Use this example to import the `version` function and retrieve the current operating system's version string. ```javascript import { version } from '@tauri-apps/plugin-os'; const osVersion = version(); ``` -------------------------------- ### Install a Base Snap Source: https://v2.tauri.app/distribute/snapcraft Install a base snap, such as core22, which provides the fundamental runtime environment for your application. ```bash sudo snap install core22 ``` -------------------------------- ### install() Source: https://v2.tauri.app/reference/javascript/updater Install downloaded updater package. ```APIDOC ## METHOD install() ### Description Installs the previously downloaded updater package. ### Returns - **Promise** - A promise that resolves when the installation is complete. ``` -------------------------------- ### Install JavaScript Guest Bindings with pnpm Source: https://v2.tauri.app/plugin/window-state Install the JavaScript guest bindings for the window-state plugin using pnpm. ```bash pnpm add @tauri-apps/plugin-window-state ``` -------------------------------- ### Selenium Test Setup and Example with Mocha for Tauri Source: https://v2.tauri.app/develop/tests/webdriver/example/selenium This comprehensive JavaScript file demonstrates how to configure Selenium WebDriver with `tauri-driver` for testing a Tauri application using Mocha. It includes `before` and `after` hooks for setup and teardown, along with example UI tests. ```javascript import os from 'os'; import path from 'path'; import { expect } from 'chai'; import { spawn, spawnSync } from 'child_process'; import { Builder, By, Capabilities } from 'selenium-webdriver'; import { fileURLToPath } from 'url'; const __dirname = fileURLToPath(new URL('.', import.meta.url)); // create the path to the expected application binary const application = path.resolve( __dirname, '..', '..', 'src-tauri', 'target', 'debug', 'tauri-app' ); // keep track of the webdriver instance we create let driver; // keep track of the tauri-driver process we start let tauriDriver; let exit = false; before(async function () { // set timeout to 2 minutes to allow the program to build if it needs to this.timeout(120000); // ensure the app has been built spawnSync('yarn', ['tauri', 'build', '--debug', '--no-bundle'], { cwd: path.resolve(__dirname, '../..'), stdio: 'inherit', shell: true, }); // start tauri-driver tauriDriver = spawn( path.resolve(os.homedir(), '.cargo', 'bin', 'tauri-driver'), [], { stdio: [null, process.stdout, process.stderr] } ); tauriDriver.on('error', (error) => { console.error('tauri-driver error:', error); process.exit(1); }); tauriDriver.on('exit', (code) => { if (!exit) { console.error('tauri-driver exited with code:', code); process.exit(1); } }); const capabilities = new Capabilities(); capabilities.set('tauri:options', { application }); capabilities.setBrowserName('wry'); // start the webdriver client driver = await new Builder() .withCapabilities(capabilities) .usingServer('http://127.0.0.1:4444/') .build(); }); after(async function () { // stop the webdriver session await closeTauriDriver(); }); describe('Hello Tauri', () => { it('should be cordial', async () => { const text = await driver.findElement(By.css('body > h1')).getText(); expect(text).to.match(/^[hH]ello/); }); it('should be excited', async () => { const text = await driver.findElement(By.css('body > h1')).getText(); expect(text).to.match(/!$/); }); it('should be easy on the eyes', async () => { // selenium returns color css values as rgb(r, g, b) const text = await driver .findElement(By.css('body')) .getCssValue('background-color'); const rgb = text.match(/^rgb\((?\d+), (?\d+), (?\d+)\)$/).groups; expect(rgb).to.have.all.keys('r', 'g', 'b'); const luma = 0.2126 * rgb.r + 0.7152 * rgb.g + 0.0722 * rgb.b; expect(luma).to.be.lessThan(100); }); }); async function closeTauriDriver() { exit = true; // kill the tauri-driver process tauriDriver.kill(); // stop the webdriver session await driver.quit(); } function onShutdown(fn) { const cleanup = () => { try { fn(); } finally { process.exit(); } }; process.on('exit', cleanup); process.on('SIGINT', cleanup); process.on('SIGTERM', cleanup); process.on('SIGHUP', cleanup); process.on('SIGBREAK', cleanup); } onShutdown(() => { closeTauriDriver(); }); ``` -------------------------------- ### Install JavaScript Guest Bindings with Deno Source: https://v2.tauri.app/plugin/deep-linking Use Deno to install the JavaScript guest bindings for the deep-link plugin. ```bash deno add npm:@tauri-apps/plugin-deep-link ``` -------------------------------- ### Install Autostart Plugin JavaScript Bindings Source: https://v2.tauri.app/plugin/autostart Install the JavaScript guest bindings for the autostart plugin using a package manager to enable frontend interaction. ```shell npm install @tauri-apps/plugin-autostart ``` ```shell yarn add @tauri-apps/plugin-autostart ``` ```shell pnpm add @tauri-apps/plugin-autostart ``` ```shell deno add npm:@tauri-apps/plugin-autostart ``` ```shell bun add @tauri-apps/plugin-autostart ``` -------------------------------- ### Install cargo-xwin Source: https://v2.tauri.app/distribute/windows-installer Install `cargo-xwin` to manage Windows SDKs for cross-compilation. ```bash cargo install --locked cargo-xwin ``` -------------------------------- ### Implement Plugin Setup Lifecycle Hook in Rust Source: https://v2.tauri.app/develop/plugins Illustrates how to use the `setup` hook to manage application state, register mobile plugins, or run background tasks when the plugin is initialized. ```rust use tauri::{Manager, plugin::Builder}; use std::{collections::HashMap, sync::Mutex, time::Duration}; struct DummyStore(Mutex>); Builder::new("") .setup(|app, api| { app.manage(DummyStore(Default::default())); let app_ = app.clone(); std::thread::spawn(move || { loop { app_.emit("tick", ()); std::thread::sleep(Duration::from_secs(1)); } }); Ok(()) }) ``` -------------------------------- ### Install JavaScript Guest Bindings with Bun Source: https://v2.tauri.app/plugin/logging Installs the JavaScript guest bindings for the Tauri log plugin using Bun. ```bash bun add @tauri-apps/plugin-log ``` -------------------------------- ### Example Tauri Configuration File (JSON) Source: https://v2.tauri.app/reference/config Illustrates a complete `tauri.conf.json` file structure, defining product name, version, build settings, app window properties, and empty bundle/plugins configurations. ```json { "productName": "tauri-app", "version": "0.1.0", "build": { "beforeBuildCommand": "", "beforeDevCommand": "", "devUrl": "http://localhost:3000", "frontendDist": "../dist" }, "app": { "security": { "csp": null }, "windows": [ { "fullscreen": false, "height": 600, "resizable": true, "title": "Tauri App", "width": 800 } ] }, "bundle": {}, "plugins": {} } ``` -------------------------------- ### Install JavaScript Guest Bindings with npm Source: https://v2.tauri.app/plugin/deep-linking Use npm to install the JavaScript guest bindings for the deep-link plugin. ```bash npm install @tauri-apps/plugin-deep-link ``` -------------------------------- ### JavaScript: Load a Store Instance Source: https://v2.tauri.app/reference/javascript/store This example shows how to load a store from a specified path, creating it if it doesn't exist. ```javascript import { Store } from '@tauri-apps/api/store'; const store = await Store.load('store.json'); ``` -------------------------------- ### Resolve Resource Path in Rust Setup Hook Source: https://v2.tauri.app/develop/resources Use `app.path().resolve` within the `setup` hook to get the path to a resource file. ```Rust tauri::Builder::default() .setup(|app| { let resource_path = app.path().resolve("lang/de.json", BaseDirectory::Resource)?; Ok(()) }) ``` -------------------------------- ### Debug RPM Installation and Upgrade with Verbose Output Source: https://v2.tauri.app/distribute/rpm Employ the `-vv` (very verbose) option during installation or upgrade to get detailed output for troubleshooting issues. ```bash rpm -ivvh package_name.rpm ``` ```bash rpm -Uvvh package_name.rpm ``` -------------------------------- ### Install JavaScript Guest Bindings with Deno Source: https://v2.tauri.app/plugin/logging Installs the JavaScript guest bindings for the Tauri log plugin using Deno. ```bash deno add npm:@tauri-apps/plugin-log ``` -------------------------------- ### Microsoft Store Silent Install Rejection Error Source: https://v2.tauri.app/distribute/microsoft-store Example of an error message received when a Win32 product submitted to the Microsoft Store does not support silent installation. ```text 10.2.9.2 Security - Package Submissions | Win32 products must install silently. ``` -------------------------------- ### Example WiX Localization File (XML) Source: https://v2.tauri.app/distribute/windows-installer An example XML file defining localization strings for a WiX installer, referenced by `localePath`. The `Culture` attribute must match the configured language. ```xml Launch MyApplicationName A newer version of MyApplicationName is already installed. Add the install location of the MyApplicationName executable to the PATH system environment variable. This allows the MyApplicationName executable to be called from any location. Installs MyApplicationName. ``` -------------------------------- ### Install File System Plugin Guest Bindings with npm Source: https://v2.tauri.app/plugin/file-system Install the JavaScript guest bindings for the file system plugin using npm. ```bash npm install @tauri-apps/plugin-fs ``` -------------------------------- ### Get Sqlite Database Instance (JavaScript) Source: https://v2.tauri.app/reference/javascript/sql Initializes a connection to an Sqlite database using the `get` method. The path is relative to `tauri::path::BaseDirectory::App` and must start with `sqlite:`. ```javascript const db = Database.get("sqlite:test.db"); ``` -------------------------------- ### Get Directory Size with Tauri FS Plugin Source: https://v2.tauri.app/reference/javascript/fs Use `size` to calculate the total size of a directory, including all its contents. This example gets the size of the 'tauri' directory within the application's data directory. ```javascript import { size, BaseDirectory } from '@tauri-apps/plugin-fs'; // Get the size of the `$APPDATA/tauri` directory. const dirSize = await size('tauri', { baseDir: BaseDirectory.AppData }); console.log(dirSize); // 1024 ``` -------------------------------- ### Install File System Plugin Guest Bindings with Deno Source: https://v2.tauri.app/plugin/file-system Install the JavaScript guest bindings for the file system plugin using Deno. ```bash deno add npm:@tauri-apps/plugin-fs ``` -------------------------------- ### Get File Information with Tauri FS Plugin Source: https://v2.tauri.app/reference/javascript/fs Use `stat` to retrieve detailed information about a file or directory, such as whether it's a file or directory. This example gets info for 'hello.txt' in the application's local data directory. ```javascript import { stat, BaseDirectory } from '@tauri-apps/plugin-fs'; const fileInfo = await stat("hello.txt", { baseDir: BaseDirectory.AppLocalData }); console.log(fileInfo.isFile); // true ``` -------------------------------- ### Install JavaScript Guest Bindings with npm Source: https://v2.tauri.app/plugin/logging Installs the JavaScript guest bindings for the Tauri log plugin using npm. ```bash npm install @tauri-apps/plugin-log ``` -------------------------------- ### Install File System Plugin Guest Bindings with Bun Source: https://v2.tauri.app/plugin/file-system Install the JavaScript guest bindings for the file system plugin using Bun. ```bash bun add @tauri-apps/plugin-fs ``` -------------------------------- ### Add content to post-remove script Source: https://v2.tauri.app/distribute/rpm Example content for a `postremove.sh` script, demonstrating how to print messages and access installation values. ```bash echo "-------------" echo "This is postun" echo "Install Value: $1" echo "Upgrade Value: $1" echo "Uninstall Value: $1" echo "-------------" ``` -------------------------------- ### Add content to pre-remove script Source: https://v2.tauri.app/distribute/rpm Example content for a `preremove.sh` script, demonstrating how to print messages and access installation values. ```bash echo "-------------" echo "This is preun" echo "Install Value: $1" echo "Upgrade Value: $1" echo "Uninstall Value: $1" echo "-------------" ``` -------------------------------- ### Configure a Single Window at Startup (JSON) Source: https://v2.tauri.app/reference/config Defines a single window with specified dimensions to be created when the application starts. ```json { "app": { "windows": [ { "width": 800, "height": 600 } ] } } ``` -------------------------------- ### Get Current Webview Physical Size in JavaScript Source: https://v2.tauri.app/reference/javascript/api/namespacewebview Retrieve the physical size of the webview's client area using this example. ```javascript import { getCurrentWebview } from '@tauri-apps/api/webview'; const size = await getCurrentWebview().size(); ``` -------------------------------- ### Fetch Data with HTTP Plugin in Rust Source: https://v2.tauri.app/start/migrate/from-tauri-1 Perform an HTTP GET request using `reqwest` re-exported by `tauri-plugin-http` within the setup hook. ```Rust use tauri_plugin_http::reqwest; tauri::Builder::default() .plugin(tauri_plugin_http::init()) .setup(|app| { let response_data = tauri::async_runtime::block_on(async { let response = reqwest::get( "https://raw.githubusercontent.com/tauri-apps/tauri/dev/package.json", ) .await .unwrap(); response.text().await })?; Ok(()) }) ``` -------------------------------- ### Install File System Plugin Guest Bindings with yarn Source: https://v2.tauri.app/plugin/file-system Install the JavaScript guest bindings for the file system plugin using yarn. ```bash yarn add @tauri-apps/plugin-fs ``` -------------------------------- ### Define a Capability Configuration Source: https://v2.tauri.app/reference/acl/capability This example demonstrates a complete capability definition, granting specific filesystem write and dialog permissions to the 'main' window on macOS and Windows. ```json { "identifier": "main-user-files-write", "description": "This capability allows the `main` window on macOS and Windows access to `filesystem` write related commands and `dialog` commands to enable programmatic access to files selected by the user.", "windows": [ "main" ], "permissions": [ "core:default", "dialog:open", { "identifier": "fs:allow-write-text-file", "allow": [{ "path": "$HOME/test.txt" }] }, ], "platforms": ["macOS","windows"] } ``` -------------------------------- ### Example: Get Public Directory Path Source: https://v2.tauri.app/reference/javascript/api/namespacepath Illustrates how to asynchronously retrieve the user's public directory path using the `publicDir` function. ```javascript import { publicDir } from '@tauri-apps/api/path'; const publicDirPath = await publicDir(); ``` -------------------------------- ### Example: Get Picture Directory Path Source: https://v2.tauri.app/reference/javascript/api/namespacepath Illustrates how to asynchronously retrieve the user's picture directory path using the `pictureDir` function. ```javascript import { pictureDir } from '@tauri-apps/api/path'; const pictureDirPath = await pictureDir(); ``` -------------------------------- ### Configure Debian Bundle Source: https://v2.tauri.app/reference/config Example configuration for the Debian bundle, defining files to be included. ```json { "files": {} } ``` -------------------------------- ### Install File System Plugin Guest Bindings with pnpm Source: https://v2.tauri.app/plugin/file-system Install the JavaScript guest bindings for the file system plugin using pnpm. ```bash pnpm add @tauri-apps/plugin-fs ``` -------------------------------- ### Get Current OS Hostname (JavaScript) Source: https://v2.tauri.app/reference/javascript/os Use this example to asynchronously retrieve the operating system's hostname. The result can be null if the hostname cannot be obtained. ```javascript import { hostname } from '@tauri-apps/plugin-os'; const hostname = await hostname(); ``` -------------------------------- ### Configure RPM Bundle Source: https://v2.tauri.app/reference/config Example configuration for the RPM bundle, including epoch, files, and release version. ```json { "epoch": 0, "files": {}, "release": "1" } ``` -------------------------------- ### Get Current OS Family (JavaScript) Source: https://v2.tauri.app/reference/javascript/os Use this example to import the `family` function and retrieve the current operating system family, such as 'unix' or 'windows'. ```javascript import { family } from '@tauri-apps/plugin-os'; const family = family(); ``` -------------------------------- ### Initialize Tauri project within Qwik app Source: https://v2.tauri.app/start/frontend/qwik Sets up the basic Tauri project structure and configuration files. ```shell npm run tauri init ``` ```shell yarn tauri init ``` ```shell pnpm tauri init ``` ```shell deno task tauri init ``` -------------------------------- ### getCurrent() Source: https://v2.tauri.app/reference/javascript/deep-link Get the current URLs that triggered the deep link. Use this on app load to check whether your app was started via a deep link. ```APIDOC ## Function: getCurrent() ### Description Get the current URLs that triggered the deep link. Use this on app load to check whether your app was started via a deep link. ### Signature ```typescript function getCurrent(): Promise ``` ### Returns `Promise` ### Example ```javascript import { getCurrent } from '@tauri-apps/plugin-deep-link'; const urls = await getCurrent(); ``` ``` -------------------------------- ### Add AndroidX Window and Startup Dependencies Source: https://v2.tauri.app/learn/mobile-multiwindow Add these libraries to your `build.gradle.kts` file to enable Activity Embedding and the startup initializer. ```Kotlin dependencies { // ... existing dependencies implementation("androidx.window:window:1.5.0") implementation("androidx.startup:startup-runtime:1.2.0") } ``` -------------------------------- ### Get General RPM Package Information Source: https://v2.tauri.app/distribute/rpm Use this command to retrieve basic details about an RPM package file, such as its version, release, and architecture, before installation. ```bash rpm -qip package_name.rpm ``` -------------------------------- ### Example Tauri Initialization Prompt Source: https://v2.tauri.app/start/create-project This output shows the interactive prompts and typical responses when initializing a Tauri project, configuring app name, window title, asset location, dev server URL, and build commands. ```shell ✔ What is your app name? tauri-app ✔ What should the window title be? tauri-app ✔ Where are your web assets located? .. ✔ What is the url of your dev server? http://localhost:5173 ✔ What is your frontend dev command? pnpm run dev ✔ What is your frontend build command? pnpm run build ``` -------------------------------- ### Configure nvim-dap-ui to Toggle Debugger View Automatically Source: https://v2.tauri.app/develop/debug/neovim This setup automatically opens the nvim-dap-ui debugger view when a session starts and closes it when the session terminates or exits. ```lua local dapui = require("dapui") dapui.setup() dap.listeners.before.attach.dapui_config = function() dapui.open() end dap.listeners.before.launch.dapui_config = function() dapui.open() end dap.listeners.before.event_terminated.dapui_config = function() dapui.close() end dap.listeners.before.event_exited.dapui_config = function() dapui.close() end ``` -------------------------------- ### Example: Get Local Data Directory Path Source: https://v2.tauri.app/reference/javascript/api/namespacepath Illustrates how to asynchronously retrieve the user's local data directory path using the `localDataDir` function. ```javascript import { localDataDir } from '@tauri-apps/api/path'; const localDataDirPath = await localDataDir(); ``` -------------------------------- ### Initialize and Run a Verso Webview Source: https://v2.tauri.app/blog/tauri-verso-integration This snippet demonstrates how to initialize and run a basic Verso webview, setting up a maximized window that loads 'https://example.com'. It requires the `versoview` executable to be located alongside the current executable. ```Rust use std::env::current_exe; use std::thread::sleep; use std::time::Duration; use url::Url; use verso::VersoBuilder; fn main() { let versoview_path = current_exe().unwrap().parent().unwrap().join("versoview"); let controller = VersoBuilder::new() .with_panel(true) .maximized(true) .build(versoview_path, Url::parse("https://example.com").unwrap()); loop { sleep(Duration::MAX); } } ``` -------------------------------- ### Create a new Qwik app Source: https://v2.tauri.app/start/frontend/qwik Initializes a new Qwik project using the specified package manager. ```shell npm create qwik@latest cd ``` ```shell yarn create qwik@latest cd ``` ```shell pnpm create qwik@latest cd ``` ```shell deno run -A npm:create-qwik@latest cd ``` -------------------------------- ### Get Current OS Type (JavaScript) Source: https://v2.tauri.app/reference/javascript/os Use this example to import the `type` function and retrieve the general operating system type, such as 'linux', 'macos', or 'windows'. ```javascript import { type } from '@tauri-apps/plugin-os'; const osType = type(); ``` -------------------------------- ### Install Global Shortcut JavaScript Guest Bindings Source: https://v2.tauri.app/plugin/global-shortcut Install the JavaScript guest bindings for the global-shortcut plugin using your preferred JavaScript package manager. ```bash npm install @tauri-apps/plugin-global-shortcut ``` ```bash yarn add @tauri-apps/plugin-global-shortcut ``` ```bash pnpm add @tauri-apps/plugin-global-shortcut ``` ```bash deno add npm:@tauri-apps/plugin-global-shortcut ``` ```bash bun add @tauri-apps/plugin-global-shortcut ``` -------------------------------- ### Get Current OS Platform (JavaScript) Source: https://v2.tauri.app/reference/javascript/os Use this example to import the `platform` function and retrieve a string identifying the specific operating system, such as 'linux' or 'windows'. ```javascript import { platform } from '@tauri-apps/plugin-os'; const platformName = platform(); ``` -------------------------------- ### Get Executable File Extension (JavaScript) Source: https://v2.tauri.app/reference/javascript/os Use this example to import the `exeExtension` function and retrieve the file extension used for executable binaries on the current platform. ```javascript import { exeExtension } from '@tauri-apps/plugin-os'; const exeExt = exeExtension(); ``` -------------------------------- ### Tauri Plugin Init Command Help Output Source: https://v2.tauri.app/reference/cli Displays the usage, arguments, and options available for the `tauri plugin init` command, including flags for API, example project, directory, author, and mobile platform initialization. ```Shell Initialize a Tauri plugin project on an existing directory Usage: tauri plugin init [OPTIONS] [PLUGIN_NAME] Arguments: [PLUGIN_NAME] Name of your Tauri plugin. If not specified, it will be inferred from the current directory Options: --no-api Initializes a Tauri plugin without the TypeScript API -v, --verbose... Enables verbose logging --no-example Initialize without an example project -d, --directory Set target directory for init [default: /opt/build/repo/packages/cli-generator] -a, --author Author name --android Whether to initialize an Android project for the plugin --ios Whether to initialize an iOS project for the plugin --mobile Whether to initialize Android and iOS projects for the plugin --ios-framework Type of framework to use for the iOS project [default: spm] Possible values: - spm: Swift Package Manager project - xcode: Xcode project --github-workflows Generate github workflows -t, --tauri-path Path of the Tauri project to use (relative to the cwd) -h, --help Print help (see a summary with '-h') -V, --version Print version ``` -------------------------------- ### init(): Promise Source: https://v2.tauri.app/reference/javascript/store Initializes or loads the store if it has not been loaded already. ```APIDOC ## METHOD init() ### Description Init/load the store if it’s not loaded already. ### Returns `Promise` ``` -------------------------------- ### Get Current OS Architecture (JavaScript) Source: https://v2.tauri.app/reference/javascript/os Use this example to import the `arch` function from the Tauri OS plugin and retrieve the current operating system architecture. ```javascript import { arch } from '@tauri-apps/plugin-os'; const archName = arch(); ``` -------------------------------- ### Initialize Node.js Project with npm Source: https://v2.tauri.app/learn/sidecar-nodejs Initializes a new Node.js project using npm in the current directory. ```bash npm init ``` -------------------------------- ### Rust Backend for Update Checking and Installation Source: https://v2.tauri.app/plugin/updater This Rust module defines the necessary commands and structures for fetching and installing updates, including error handling, download event serialization, and managing pending updates. It also illustrates the main application setup to integrate the updater plugin and expose these commands. ```Rust #[cfg(desktop)] mod app_updates { use std::sync::Mutex; use serde::Serialize; use tauri::{ipc::Channel, AppHandle, State}; use tauri_plugin_updater::{Update, UpdaterExt}; #[derive(Debug, thiserror::Error)] pub enum Error { #[error(transparent)] Updater(#[from] tauri_plugin_updater::Error), #[error("there is no pending update")] NoPendingUpdate, } impl Serialize for Error { fn serialize(&self, serializer: S) -> std::result::Result where S: serde::Serializer, { serializer.serialize_str(self.to_string().as_str()) } } type Result = std::result::Result; #[derive(Clone, Serialize)] #[serde(tag = "event", content = "data")] pub enum DownloadEvent { #[serde(rename_all = "camelCase")] Started { content_length: Option, }, #[serde(rename_all = "camelCase")] Progress { chunk_length: usize, }, Finished, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] pub struct UpdateMetadata { version: String, current_version: String, } #[tauri::command] pub async fn fetch_update( app: AppHandle, pending_update: State<'_, PendingUpdate>, ) -> Result> { let channel = "stable"; let url = url::Url::parse(&format!( "https://cdn.myupdater.com/{{{{target}}}}-{{{{arch}}}}/{{{{current_version}}}}?channel={channel}", )).expect("invalid URL"); let update = app .updater_builder() .endpoints(vec![url])? .build()?Н .check() .await?; let update_metadata = update.as_ref().map(|update| UpdateMetadata { version: update.version.clone(), current_version: update.current_version.clone(), }); *pending_update.0.lock().unwrap() = update; Ok(update_metadata) } #[tauri::command] pub async fn install_update(pending_update: State<'_, PendingUpdate>, on_event: Channel) -> Result<()> { let Some(update) = pending_update.0.lock().unwrap().take() else { return Err(Error::NoPendingUpdate); }; let started = false; update .download_and_install( |chunk_length, content_length| { if !started { let _ = on_event.send(DownloadEvent::Started { content_length }); started = true; } let _ = on_event.send(DownloadEvent::Progress { chunk_length }); }, || { let _ = on_event.send(DownloadEvent::Finished); }, ) .await?; Ok(()) } struct PendingUpdate(Mutex>); } #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_process::init()) .setup(|app| { #[cfg(desktop)] { app.handle().plugin(tauri_plugin_updater::Builder::new().build()); app.manage(app_updates::PendingUpdate(Mutex::new(None))); } Ok(()) }) .invoke_handler(tauri::generate_handler![ #[cfg(desktop)] app_updates::fetch_update, #[cfg(desktop)] app_updates::install_update ]) } ``` -------------------------------- ### new Client(path, name) Source: https://v2.tauri.app/reference/javascript/stronghold Constructs a new `Client` instance for interacting with Stronghold. ```APIDOC ## Constructor: new Client(path, name) ### Description Constructs a new `Client` instance for interacting with Stronghold. ### Parameters - **path** (string) - Required - The path for the client. - **name** (ClientPath) - Required - The name of the client. ### Returns `Client` ``` -------------------------------- ### Get Current OS Locale (JavaScript) Source: https://v2.tauri.app/reference/javascript/os Use this example to asynchronously retrieve the operating system's locale. Check if the returned `locale` string is not null before using it. ```javascript import { locale } from '@tauri-apps/plugin-os'; const locale = await locale(); if (locale) { // use the locale string here } ``` -------------------------------- ### enable() Source: https://v2.tauri.app/reference/javascript/autostart Enables the autostart feature for the application, allowing it to launch automatically on system startup. ```APIDOC ## enable() ### Description Enables the autostart feature for the application. ### Method `enable()` ### Parameters No parameters. ### Returns `Promise` - A Promise that resolves when the autostart feature has been enabled. ### Request Example ```javascript await enable(); ``` ### Response #### Success Response `Promise` - Indicates successful enabling of autostart. ``` -------------------------------- ### Example Usage of fetch() to Retrieve JSON Source: https://v2.tauri.app/reference/javascript/http Demonstrates how to use `fetch()` to make an HTTP GET request, retrieve JSON data, and log the response status and text. ```javascript const response = await fetch("http://my.json.host/data.json"); console.log(response.status); // e.g. 200 console.log(response.statusText); // e.g. "OK" const jsonData = await response.json(); ``` -------------------------------- ### Initialize, Set, and Get Store in Rust Source: https://v2.tauri.app/plugin/store Integrate the store plugin into your Tauri application. This example shows how to create a store, set a JSON value, and retrieve it from the store. ```rust use tauri::Wry; use tauri_plugin_store::StoreExt; use serde_json::json; #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_store::Builder::default().build()) .setup(|app| { // Create a new store or load the existing one // this also put the store in the app's resource table // so your following `store` calls (from both Rust and JS) // will reuse the same store. let store = app.store("store.json")?; // Note that values must be serde_json::Value instances, // otherwise, they will not be compatible with the JavaScript bindings. store.set("some-key", json!({ "value": 5 })); // Get a value from the store. let value = store.get("some-key").expect("Failed to get value from store"); println!("{}", value); // {"value":5} // Remove the store from the resource table store.close_resource(); Ok(()) }) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Scaffold WebdriverIO Project Source: https://v2.tauri.app/develop/tests/webdriver Use this command to quickly set up a new WebdriverIO project. Select 'Desktop Testing' and 'Tauri' during the interactive prompt. ```bash npm create wdio@latest ./ ``` -------------------------------- ### Initialize Mutable State with Mutex in Tauri Source: https://v2.tauri.app/develop/state-management This example shows how to manage mutable application state by wrapping it in a `std::sync::Mutex` during Tauri application setup to prevent data races. ```Rust use std::sync::Mutex; use tauri::{Builder, Manager}; #[derive(Default)] struct AppState { counter: u32, } fn main() { Builder::default() .setup(|app| { app.manage(Mutex::new(AppState::default())); Ok(()) }) .run(tauri::generate_context!()) .unwrap(); } ``` -------------------------------- ### Adjusting File Position with FileHandle.seek() in JavaScript Source: https://v2.tauri.app/reference/javascript/fs This example shows how to open a file, write initial content, and then use `seek()` with different `SeekMode` values (`Start`, `Current`, `End`) to reposition the file cursor. ```javascript import { open, SeekMode, BaseDirectory } from '@tauri-apps/plugin-fs'; // Given hello.txt pointing to file with "Hello world", which is 11 bytes long: const file = await open('hello.txt', { read: true, write: true, truncate: true, create: true, baseDir: BaseDirectory.AppLocalData }); await file.write(new TextEncoder().encode("Hello world")); // Seek 6 bytes from the start of the file console.log(await file.seek(6, SeekMode.Start)); // "6" // Seek 2 more bytes from the current position console.log(await file.seek(2, SeekMode.Current)); // "8" // Seek backwards 2 bytes from the end of the file console.log(await file.seek(-2, SeekMode.End)); // "9" (e.g. 11-2) await file.close(); ``` -------------------------------- ### Install JavaScript Guest Bindings for Store Plugin Source: https://v2.tauri.app/plugin/store Install the JavaScript guest bindings for the Store plugin using your preferred package manager. ```bash npm install @tauri-apps/plugin-store ``` ```bash yarn add @tauri-apps/plugin-store ``` ```bash pnpm add @tauri-apps/plugin-store ``` ```bash deno add npm:@tauri-apps/plugin-store ``` ```bash bun add @tauri-apps/plugin-store ``` -------------------------------- ### Tauri iOS Init Command Line Interface Help Source: https://v2.tauri.app/reference/cli Displays the available options for the `tauri ios init` command, including flags for CI, verbose logging, dependency reinstallation, and configuration. ```bash Initialize iOS target in the project Usage: tauri ios init [OPTIONS] Options: --ci Skip prompting for values [env: CI=] -v, --verbose... Enables verbose logging -r, --reinstall-deps Reinstall dependencies --skip-targets-install Skips installing rust toolchains via rustup -c, --config JSON strings or paths to JSON, JSON5 or TOML files to merge with the default configuration file Configurations are merged in the order they are provided, which means a particular value overwrites previous values when a config key-value pair conflicts. Note that a platform-specific file is looked up and merged with the default file by default (tauri.macos.conf.json, tauri.linux.conf.json, tauri.windows.conf.json, tauri.android.conf.json and tauri.ios.conf.json) but you can use this for more specific use cases such as different build flavors. -h, --help Print help (see a summary with '-h') -V, --version Print version ``` -------------------------------- ### Create Multi-level Application Menu in Rust Source: https://v2.tauri.app/learn/window-menu This example demonstrates how to build multi-level menus, including checkable items and icons, within a Tauri application's setup function. It also shows how to dynamically update submenu icons. ```Rust use tauri::{ image::Image, menu::{CheckMenuItemBuilder, IconMenuItemBuilder, MenuBuilder, SubmenuBuilder}, }; fn main() { tauri::Builder::default() .setup(|app| { let menu_image = Image::from_bytes(include_bytes!("../icons/menu.png")).unwrap(); let file_menu = SubmenuBuilder::new(app, "File") .submenu_icon(menu_image) // Optional: Add an icon to the submenu .text("open", "Open") .text("quit", "Quit") .build()?; let lang_str = "en"; let check_sub_item_1 = CheckMenuItemBuilder::new("English") .id("en") .checked(lang_str == "en") .build(app)?; let check_sub_item_2 = CheckMenuItemBuilder::new("Chinese") .id("zh") .checked(lang_str == "zh") .enabled(false) .build(app)?; // Load icon from path let icon_image = Image::from_bytes(include_bytes!("../icons/icon.png")).unwrap(); let icon_item = IconMenuItemBuilder::new("icon") .icon(icon_image) .build(app)?; let other_item = SubmenuBuilder::new(app, "language") .item(&check_sub_item_1) .item(&check_sub_item_2) .build()?; let menu = MenuBuilder::new(app) .items(&[&file_menu, &other_item, &icon_item]) .build()?; app.set_menu(menu)?; let menu_image_update = Image::from_bytes(include_bytes!("../icons/menu_update.png")).unwrap(); // You can also update the submenu icon dynamically file_menu.set_icon(Some(menu_image_update))?; // Or set a native icon (only one type applies per platform) file_menu.set_native_icon(Some(tauri::menu::NativeIcon::Folder))?; Ok(()) }) .run(tauri::generate_context!()); } ``` -------------------------------- ### Configure Per-Machine Install Mode for Windows Installer Source: https://v2.tauri.app/distribute/windows-installer Set the `installMode` to `perMachine` to install the application system-wide. This option requires Administrator privileges during installation. ```json { "bundle": { "windows": { "nsis": { "installMode": "perMachine" } } } } ``` -------------------------------- ### Initialize Tauri Backend Source: https://v2.tauri.app/start/create-project Run this command in your project directory to initialize the Tauri backend, which will create the `src-tauri` directory and prompt for configuration options. ```npm npx tauri init ``` ```yarn yarn tauri init ``` ```pnpm pnpm tauri init ``` ```deno deno task tauri init ``` ```bun bun tauri init ``` ```cargo cargo tauri init ``` -------------------------------- ### Configure WebView2 Offline Installer (JSON) Source: https://v2.tauri.app/distribute/windows-installer Set webviewInstallMode to "offlineInstaller" in tauri.conf.json to embed the full WebView2 installer, enabling offline installation but significantly increasing installer size. ```JSON { "bundle": { "windows": { "webviewInstallMode": { "type": "offlineInstaller" } } } } ``` -------------------------------- ### Bundling Dependencies for NSIS Installer Source: https://v2.tauri.app/distribute/windows-installer Add dependency installers to the `resources` array in `tauri.conf.json` so they are bundled with your application and accessible during installation. ```JSON { "bundle": { "resources": [ "resources/my-dependency.exe", "resources/another-one.msi ] } } ``` -------------------------------- ### Initialize, Set, Get, and Save Store in JavaScript Source: https://v2.tauri.app/plugin/store Use `load` to create or retrieve a store instance. This snippet demonstrates how to set and retrieve values, and manually save changes to disk. ```javascript import { load } from '@tauri-apps/plugin-store'; // when using `"withGlobalTauri": true`, you may use // const { load } = window.__TAURI__.store; // Create a new store or load the existing one, // note that the options will be ignored if a `Store` with that path has already been created const store = await load('store.json', { autoSave: false }); // Set a value. await store.set('some-key', { value: 5 }); // Get a value. const val = await store.get<{ value: number }>('some-key'); console.log(val); // { value: 5 } // You can manually save the store after making changes. // Otherwise, it will save upon graceful exit // And if you set `autoSave` to a number or left empty, // it will save the changes to disk after a debounce delay, 100ms by default. await store.save(); ``` -------------------------------- ### Install Homebrew on macOS Source: https://v2.tauri.app/start/prerequisites Install Homebrew, the macOS package manager, which is often a prerequisite for installing other development tools like Cocoapods. ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` -------------------------------- ### Install Opener JavaScript Guest Bindings Source: https://v2.tauri.app/plugin/opener Installs the JavaScript guest bindings for the Opener plugin using your preferred package manager. ```npm npm install @tauri-apps/plugin-opener ``` ```yarn yarn add @tauri-apps/plugin-opener ``` ```pnpm pnpm add @tauri-apps/plugin-opener ``` ```deno deno add npm:@tauri-apps/plugin-opener ``` ```bun bun add @tauri-apps/plugin-opener ``` -------------------------------- ### Install dependencies and run the Tauri application Source: https://v2.tauri.app/learn/splashscreen Navigate to the project directory, install the necessary dependencies, and then build and run the Tauri application in development mode. ```Shell # Make sure you're in the right directory cd splashscreen-lab # Install dependencies pnpm install # Build and run the app pnpm tauri dev ``` -------------------------------- ### Install Tauri CLI with cargo-binstall Source: https://v2.tauri.app/blog/tauri-1-1 Install `cargo-binstall` and then use it to install the Tauri CLI, enabling the use of `cargo tauri` commands. ```shell $ cargo install cargo-binstall $ cargo binstall tauri-cli $ cargo tauri dev # run any Tauri command! ```