Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Commands and Events

Tauri Events: emit, listen and Messaging Between Windows

Send messages both ways with Tauri events: emit and listen in Rust and JavaScript, typed payloads, targeting windows, one-time listeners, unlistening and when to use commands instead.

Commands are request and response: the frontend asks, Rust answers. Events are fire-and-forget messages that can go in either direction, with no reply. They suit things that happen: a download finished, the user chose a menu item, another window saved a file.

Commands versus events

Command Event
Direction Frontend to Rust Either way
Reply Yes, a Promise No
Type safety Strong (Rust types) Payload is JSON
Best for "Do this and tell me the result" "Something happened"

Rule of thumb: if you need an answer, use a command. If you are announcing, use an event.

Rust to frontend

Import the Emitter trait and call emit on an AppHandle, a window or a webview window.

Rust
use serde::Serialize;
use tauri::{AppHandle, Emitter};

#[derive(Clone, Serialize)]
struct DownloadProgress {
    file: String,
    percent: u8,
}

#[tauri::command]
fn start_download(app: AppHandle, file: String) {
    tauri::async_runtime::spawn(async move {
        for percent in (0..=100).step_by(25) {
            let _ = app.emit("download-progress", DownloadProgress { file: file.clone(), percent });
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        }
    });
}

The payload type must be Serialize + Clone. emit sends to every window and webview.

In JavaScript, listen with listen. It returns a Promise for an unlisten function:

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

const unlisten = await listen<{ file: string; percent: number }>("download-progress", (event) => {
  console.log(event.payload.file, event.payload.percent);
});

// later, when the component goes away:
unlisten();

Always unlisten when a component unmounts, or you collect duplicate handlers every time the component is created. In React, do it in the effect cleanup:

TSX
useEffect(() => {
  const promise = listen<number>("tick", (e) => setValue(e.payload));
  return () => { promise.then((unlisten) => unlisten()); };
}, []);

The event object has event (the name), id (listener id) and payload.

Frontend to Rust

JavaScript can emit too, and Rust listens through the Listener trait:

TypeScript
import { emit } from "@tauri-apps/api/event";
await emit("user-clicked", { button: "save" });
Rust
use tauri::{Listener, Manager};

pub fn run() {
    tauri::Builder::default()
        .setup(|app| {
            let handle = app.handle().clone();
            app.listen("user-clicked", move |event| {
                println!("payload: {}", event.payload()); // a JSON string
                let _ = handle.emit("ack", "got it");
            });
            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error");
}

In Rust the payload arrives as a JSON string; parse it with serde_json::from_str. Use app.once("name", ...) to run a listener a single time and app.unlisten(id) to remove one by the id that listen returns.

Targeting a window

Sometimes only one window should hear about something.

Rust
use tauri::{Emitter, Manager};

// to one window by label
app.emit_to("settings", "theme-changed", "dark")?;

// to every window matching a filter
app.emit_filter("refresh", (), |target| match target {
    tauri::EventTarget::WebviewWindow { label } => label.starts_with("doc-"),
    _ => false,
})?;

JavaScript can listen on one window only with getCurrentWindow().listen(...), which hears events aimed at that window plus global ones.

Event names

Names may contain letters, digits and -, /, : and _. A common convention is domain:action, for example download:progress. Keep a single place, a TypeScript constant file, listing names so frontend and Rust agree.

sequenceDiagram
  participant W1 as Window A
  participant Core as Rust core
  participant W2 as Window B
  W1->>Core: emit("note-saved", id)
  Core->>W2: emit_to("B", "note-saved", id)
  Note over W2: listener updates the list

Events let windows talk through the core.

Try it: a tiny event bus (stand-in)

This JavaScript event bus has the same surface as Tauri's: listen returns an unlisten function, once fires one time, and emit can target a window.

Node.js Stand-in: emit, listen, once, unlisten

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: the listener leak (stand-in)

Forgetting to unlisten multiplies handlers. The stand-in counts what happens when a "component" mounts three times.

Node.js Stand-in: duplicate listeners

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.

Good practice

  • Treat payloads as small JSON. For large data or ordered streams, use a channel.
  • Validate event payloads in Rust before trusting them: the frontend is untrusted.
  • Events are not guaranteed to be delivered to a listener that is not yet registered. Register listeners before triggering the action that emits.
  • Prefer commands for anything that needs an answer or error handling.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When should you use an event instead of a command?

    Events are one-way notifications; commands are request and response.
  2. 2. What does listen() resolve to in JavaScript?

    Call the returned function to stop receiving events.
  3. 3. What trait must you import to call emit on an AppHandle in Rust?

    emit comes from the Emitter trait; Listener provides listen and once.
  4. 4. How does a Rust listener receive an event payload?

    event.payload() is a JSON string; parse it with serde_json.

Summary

  • Events are one-way messages that work in both directions; commands are request and response.
  • Rust uses Emitter::emit and Listener::listen; JavaScript uses emit and listen from @tauri-apps/api/event.
  • emit_to and filters target specific windows.
  • Always unlisten when a component goes away.
  • Keep payloads small, validate them, and register listeners before the action that emits.

Next: Channels and streaming data