Tauri 運(yùn)行時窗口

2024-01-29 16:19 更新

還可以通過 Rust 層或 Tauri API 在運(yùn)行時創(chuàng)建窗口。

在 Rust 中創(chuàng)建窗口

窗口可以在運(yùn)行時使用 WindowBuilder 結(jié)構(gòu)體創(chuàng)建。

要創(chuàng)建一個窗口,必須有一個正在運(yùn)行的 App 的實例或一個 AppHandle

使用 App 實例創(chuàng)建一個窗口

App 實例可以在安裝鉤子中獲取,也可以在調(diào)用 Builder::build 之后獲取。

tauri::Builder::default()
  .setup(|app| {
    let docs_window = tauri::WindowBuilder::new(
      app,
      "external", /* the unique window label */
      tauri::WindowUrl::External("https://tauri.app/".parse().unwrap())
    ).build()?;
    let local_window = tauri::WindowBuilder::new(
      app,
      "local",
      tauri::WindowUrl::App("index.html".into())
    ).build()?;
    Ok(())
  })

使用設(shè)置鉤子確保靜態(tài)窗口和 Tauri 插件已初始化?;蛘?,可以在構(gòu)建 App 后創(chuàng)建一個窗口:

let app = tauri::Builder::default()
  .build(tauri::generate_context!())
  .expect("error while building tauri application");

let docs_window = tauri::WindowBuilder::new(
  &app,
  "external", /* the unique window label */
  tauri::WindowUrl::External("https://tauri.app/".parse().unwrap())
).build().expect("failed to build window");

let local_window = tauri::WindowBuilder::new(
  &app,
  "local",
  tauri::WindowUrl::App("index.html".into())
).build()?;

當(dāng)無法將值的所有權(quán)移動到設(shè)置閉包時,此方法非常有用。

使用 AppHandle 實例創(chuàng)建一個窗口

AppHandle 實例可以使用 [] 函數(shù)獲得,也可以直接注入 Tauri 命令。?App::handle?

tauri::Builder::default()
  .setup(|app| {
    let handle = app.handle();
    std::thread::spawn(move || {
      let local_window = tauri::WindowBuilder::new(
        &handle,
        "local",
        tauri::WindowUrl::App("index.html".into())
      ).build()?;
    });
    Ok(())
  })
#[tauri::command]
async fn open_docs(handle: tauri::AppHandle) {
  let docs_window = tauri::WindowBuilder::new(
    &handle,
    "external", /* the unique window label */
    tauri::WindowUrl::External("https://tauri.app/".parse().unwrap())
  ).build().unwrap();
}

當(dāng)在 Tauri 命令中創(chuàng)建窗口時,確保命令函數(shù)是 ,以避免由于 wry#583 問題而導(dǎo)致的 windows 死鎖。async

在 JavaScript 中創(chuàng)建窗口

使用 Tauri API,可以通過導(dǎo)入 WebviewWindow 類輕松地在運(yùn)行時創(chuàng)建一個窗口。

import { WebviewWindow } from '@tauri-apps/api/window'
const webview = new WebviewWindow('theUniqueLabel', {
  url: 'path/to/page.html',
})
// since the webview window is created asynchronously,
// Tauri emits the `tauri://created` and `tauri://error` to notify you of the creation response
webview.once('tauri://created', function () {
  // webview window successfully created
})
webview.once('tauri://error', function (e) {
  // an error occurred during webview window creation
})


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號