14 Localhost

原文链接: https://tauri.app/plugin/localhost/

通过 localhost 服务器暴露应用的资源,而不是使用默认的自定义协议。

支持的平台

平台支持程度说明
Windows完整支持
Linux完整支持
macOS完整支持
Android不支持
iOS不支持

设置

安装 localhost 插件即可开始。

安装方式

自动

使用你的项目包管理器添加依赖:

1
npm run tauri add localhost
1
yarn run tauri add localhost
1
pnpm tauri add localhost
1
deno task tauri add localhost
1
bun tauri add localhost
1
cargo tauri add localhost

手动

  1. 在 src-tauri 文件夹中运行以下命令,把插件加入 Cargo.toml 里的项目依赖:

    1
    
    cargo add tauri-plugin-localhost
    
  2. 修改 lib.rs 初始化插件:

    1
    2
    3
    4
    5
    6
    7
    
    #[cfg_attr(mobile, tauri::mobile_entry_point)]
    pub fn run() {
        tauri::Builder::default()
            .plugin(tauri_plugin_localhost::Builder::new().build())
            .run(tauri::generate_context!())
            .expect("error while running tauri application");
    }
    

用法

localhost 插件在 Rust 中可用。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
use tauri::{webview::WebviewWindowBuilder, WebviewUrl};

pub fn run() {
  let port: u16 = 9527;

  tauri::Builder::default()
      .plugin(tauri_plugin_localhost::Builder::new(port).build())
      .setup(move |app| {
          let url = format!("http://localhost:{}", port).parse().unwrap();
          WebviewWindowBuilder::new(app, "main".to_string(), WebviewUrl::External(url))
              .title("Localhost Example")
              .build()?;
          Ok(())
      })
      .run(tauri::generate_context!())
      .expect("error while running tauri application");
}
最后修改 September 26, 2026: 更新 (630b11f59)