🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly web-sys: Browser APIs from Rust

web-sys gives Rust bindings for browser APIs. It covers the DOM, canvas, and fetch from Rust code.

Read the document title

This function asks the window for its document.

use wasm_bindgen::prelude::*;
use web_sys::window;

#[wasm_bindgen]
pub fn page_title() -> String {
    window().unwrap().document().unwrap().title()
}

Create an element

This function makes a paragraph and adds it to the body.

use wasm_bindgen::prelude::*;
use web_sys::window;

#[wasm_bindgen]
pub fn add_note() {
    let document = window().unwrap().document().unwrap();
    let p = document.create_element("p").unwrap();
    p.set_text_content(Some("Hello from Rust"));
    document.body().unwrap().append_child(&p).unwrap();
}

Check the window exists

This function returns true when Rust runs in a browser.

use wasm_bindgen::prelude::*;
use web_sys::window;

#[wasm_bindgen]
pub fn dom_ready() -> bool {
    window().is_some()
}

Example

console.log(typeof window);
console.log(typeof window !== "undefined" && window.document !== undefined);

Key points

  • web-sys is the crate for browser APIs.
  • The DOM is the page as objects a program can read and change.
  • Use web-sys to read the document title from Rust.
  • Use web-sys to create an element and add it to the page.
  • The window object is the browser window, so Rust reaches the page through it.

In this example, the code checks for a browser window from JavaScript. The first line reports the type of window. The second line checks that the window has a document. The web-sys window() call does the same check from Rust, and it answers true in a browser. The Rust module behind this lesson needs the full glue to load. The title and element steps stay as Rust code in the snippets.

Note

web-sys needs the right feature flags for each API used.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does web-sys give Rust?