Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Windows and Menus

Multiple Windows, Child Webviews and Window Communication

Open, reuse and coordinate several Tauri windows: spawn from JavaScript or Rust, avoid duplicates, share state, send messages between windows and add child webviews.

Settings panels, document windows, preview windows and tool palettes are all separate windows. Tauri handles them with the same labeling and events you already know. This lesson shows how to open them correctly, how to avoid common duplicates, and how they talk to each other.

Opening a window from JavaScript

TypeScript
import { WebviewWindow } from "@tauri-apps/api/webviewWindow";

const win = new WebviewWindow("settings", {
  url: "settings.html",
  title: "Settings",
  width: 520,
  height: 420,
  resizable: false,
});

win.once("tauri://created", () => console.log("window created"));
win.once("tauri://error", (e) => console.error("window failed", e));

Creation is asynchronous, so you wait for the tauri://created or tauri://error event. If a window with that label already exists, creation fails, which leads us to the next pattern.

The calling window needs the permission core:webview:allow-create-webview-window, and the new window's label must be covered by a capability if it should call commands.

Reuse instead of duplicate

A "Settings" menu item clicked twice should focus the existing window, not fail or open a second one:

TypeScript
import { WebviewWindow } from "@tauri-apps/api/webviewWindow";

export async function openSettings() {
  const existing = await WebviewWindow.getByLabel("settings");
  if (existing) {
    await existing.show();
    await existing.setFocus();
    return existing;
  }
  return new WebviewWindow("settings", { url: "settings.html", title: "Settings" });
}

The same logic in Rust:

Rust
use tauri::{AppHandle, Manager, WebviewUrl, WebviewWindowBuilder};

#[tauri::command]
fn open_settings(app: AppHandle) -> Result<(), String> {
    if let Some(window) = app.get_webview_window("settings") {
        window.show().map_err(|e| e.to_string())?;
        return window.set_focus().map_err(|e| e.to_string());
    }
    WebviewWindowBuilder::new(&app, "settings", WebviewUrl::App("settings.html".into()))
        .title("Settings")
        .inner_size(520.0, 420.0)
        .build()
        .map(|_| ())
        .map_err(|e| e.to_string())
}

Many windows of the same kind

For document windows you need unique labels. Generate them:

TypeScript
let counter = 0;
function openDocument(path: string) {
  counter += 1;
  return new WebviewWindow(`doc-${counter}`, {
    url: `/editor?path=${encodeURIComponent(path)}`,
    title: path,
  });
}

Each doc-N window is distinct. A capability can cover them all with a pattern: "windows": ["doc-*"]. In the page, read the query string to know which document to load.

Talking between windows

Windows do not share JavaScript memory. Use events (see Events) through the core:

TypeScript
import { emitTo, listen } from "@tauri-apps/api/event";

// in the editor window, after saving
await emitTo("main", "note-saved", { id: 12 });

// in the main window
await listen<{ id: number }>("note-saved", ({ payload }) => refreshNote(payload.id));

For shared data, keep one source of truth in Rust state and let each window ask for it with a command. Events tell windows when to ask.

Windows and the app lifecycle

By default the app exits when the last window closes. To keep a tray app running without windows, intercept that:

Rust
.on_window_event(|window, event| {
    if let tauri::WindowEvent::CloseRequested { api, .. } = event {
        window.hide().unwrap();   // hide instead of closing
        api.prevent_close();
    }
})

Alternatively, handle RunEvent::ExitRequested in .build(...).run(|app, event| ...) and call api.prevent_exit() to keep the process alive. The tray lesson shows this in context.

Child webviews inside one window (multiwebview)

Tauri 2 can place several webviews inside a single window, each with its own page, for layouts like a sidebar plus content area or an embedded browser pane. This is behind the unstable Cargo feature, so treat the API as subject to change.

Rust
let window = tauri::window::WindowBuilder::new(app, "main").build()?;

window.add_child(
    tauri::webview::WebviewBuilder::new("sidebar", WebviewUrl::App("sidebar.html".into())),
    tauri::LogicalPosition::new(0, 0),
    tauri::LogicalSize::new(240, 700),
)?;
window.add_child(
    tauri::webview::WebviewBuilder::new("content", WebviewUrl::App("content.html".into())),
    tauri::LogicalPosition::new(240, 0),
    tauri::LogicalSize::new(760, 700),
)?;

Each webview has its own label, can get its own permissions, and communicates through events like windows do. For most apps, one webview per window is simpler and sufficient.

Windows from another origin

You can point a window at a remote URL, but remote pages are not your code. Capabilities can be limited to remote domains with a remote section listing allowed URLs, and you should grant such pages almost nothing. Prefer opening external sites in the user's browser with the opener plugin.

Try it: open-or-focus and unique labels (stand-in)

This stand-in models the reuse pattern and the generated label pattern.

Node.js Stand-in: reuse the settings window, number the documents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Try it: messaging between windows (stand-in)

Two "windows" share nothing except messages routed through a "core". The emitter targets one label.

Node.js Stand-in: emitTo between windows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Tips

  • Give every long-lived window a descriptive, stable label.
  • Hide-and-show beats destroy-and-recreate for windows users reopen often: it is faster and keeps state.
  • Test on every platform: macOS keeps apps running after the last window closes by convention, while Windows and Linux usually quit.

Next, native menus for those windows: Menus.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you avoid opening a second 'settings' window?

    getByLabel (JS) or get_webview_window (Rust) tells you whether it already exists.
  2. 2. How do separate windows share data?

    Each webview has its own JS memory; the core is the meeting point.
  3. 3. What does api.prevent_close() do?

    It stops the window from closing so you can hide it or ask the user first.
  4. 4. Which pattern gives each document window a unique label?

    Labels must be unique; a counter or id makes them so.

Summary

  • Create windows from JavaScript or Rust; wait for the created or error signal.
  • Check for an existing label to focus it instead of duplicating.
  • Use generated labels and wildcard capabilities for document windows.
  • Coordinate windows with events and a single source of truth in Rust state.
  • Child webviews are available behind the unstable feature for layouts inside one window.

Next: Menus