skip to content

In a Rust crate using web-sys, why does `web_sys::window()?.document()` fail to compile until Cargo features are enabled, and how do js-sys and web-sys differ?

level: middleimportance: should knowfreq 25%

answer

  1. generated from WebIDL
  2. one Cargo feature per interface
  3. methods gated by the types they mention
  4. built-ins vs browser APIs

basics

~20 s

web-sys gates each Web API binding behind a Cargo feature named after its interface, so window() needs Window and Window::document also needs Document. js-sys binds JavaScript's built-ins, such as Array, Date and typed arrays; web-sys binds browser APIs.

solid answer

~40 s

web-sys is generated from the browsers' WebIDL and carries more than 1,700 Cargo features, one per interface, with only `std` on by default, so a fresh dependency exposes almost nothing. Without the `Window` feature, `web_sys::window()` fails with E0425 and a note that the item "is gated behind the `Window` feature". Methods are also gated by the interfaces their signatures use: `Window::document` returns a `Document`, so it needs both `Window` and `Document`, and without `Document` rustc reports E0599 "no method named `document` found for struct `Window`" with no hint. Each item's docs list the features it requires. js-sys covers JavaScript's standard built-ins, such as `Array`, `Date`, `Promise` and `Uint8Array`, which exist in any JavaScript host and need no per-API features. Casting between interfaces, such as `Element` to `HtmlCanvasElement`, uses `JsCast::dyn_into`.

code

toml · 17 lines
toml
[package]
name = "image-filter"
version = "0.1.0"
edition = "2024"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
wasm-bindgen = "0.2"
web-sys = { version = "0.3", features = [
    "Window",
    "Document",
    "HtmlCanvasElement",
    "CanvasRenderingContext2d",
    "ImageData",
] }

go deeper

for a junior

Recall that web-sys needs a Cargo feature for each Web API interface you use, and that js-sys covers JavaScript built-ins such as Array, Date and Promise.

for a middle

Explain the gating rule, including methods gated by the interfaces in their signatures, and read the two errors: E0425 with a configured-out note, E0599 with none.

for a senior

Show the workflow that keeps a browser crate building: features copied from each method's docs, checked downcasts with dyn_into, and the bindings kept in one crate.

for a principal

Frame the cost: every enabled interface adds compile time, so a team keeps web-sys usage in a thin bindings layer rather than spreading DOM calls through the filter code.

## Two binding crates with different scopes Both crates are built on wasm-bindgen's import machinery, and both give Rust typed handles to JavaScript values. They differ in what they bind: | | js-sys | web-sys | |---|---|---| | Binds | JavaScript's standard built-ins | Web platform APIs from WebIDL | | Examples | `Array`, `Date`, `Promise`, `Uint8Array`, `JsString` | `Window`, `Document`, `HtmlCanvasElement`, `ImageData` | | Available in | any JavaScript host | browsers, and hosts that provide those APIs | | Per-API Cargo features | none | one per interface, over 1,700 | An image filter that only needs bytes and dates can use js-sys alone; the moment it touches the page's canvas, it needs web-sys. ## Every interface is a Cargo feature web-sys is generated from the WebIDL that describes browser APIs. So that a crate compiles only the bindings it uses, each interface sits behind a **Cargo feature of the same name**, and the crate enables only `std` by default. A dependency line with no features exposes almost nothing: - `web_sys::window()` is declared under `#[cfg(feature = "Window")]`; - without that feature, rustc 1.99.1 reports E0425 "cannot find function `window` in crate `web_sys`" and adds a note that it found an item that was configured out, "gated behind the `Window` feature". That note is rustc reading the `cfg` attribute; how Cargo turns a features list into `cfg` flags, and how features unify across a dependency graph, belongs to Cargo's features material. ## Methods are gated by the types they mention The less obvious rule: web-sys also gates a method behind the **interfaces its signature uses**, and its docs list all of them. `Window::document` returns `Option<Document>`, so its binding carries `#[cfg(feature = "Document")]` inside the `Window` interface. With `Window` on and `Document` off: 1. `web_sys::window()` compiles; 2. `.document()` fails with E0599 "no method named `document` found for struct `Window` in the current scope"; 3. no note points at the missing feature, so the error reads as if the method did not exist. The rendered documentation of each item ends with a line such as "This API requires the following crate features to be activated: `Document`, `Window`", which is the list to copy into Cargo.toml. ## Casting between interfaces DOM methods return general types: `Document::get_element_by_id` returns an `Element`, and `HtmlCanvasElement::get_context` returns a generic `Object`. web-sys mirrors the inheritance chain with conversions **upward** (`Element::from(canvas)` compiles), but going **down** needs a checked cast: - `element.dyn_into::<HtmlCanvasElement>()` from wasm-bindgen's `JsCast` trait checks the JavaScript type at run time and returns `Err(element)` on a mismatch; - `element as HtmlCanvasElement` is rejected with E0605, a non-primitive cast; - `HtmlCanvasElement::from(element)` is rejected with E0277, since only the upward `From` exists. ## js-sys in practice js-sys is the right tool for data that is JavaScript's own rather than the page's: - `js_sys::Uint8Array::to_vec` copies a typed array into a Rust `Vec<u8>`, and `copy_from` copies a slice into it; - `js_sys::Date::now` returns the current time in milliseconds, which matters on a target where `std::time::Instant::now` panics; - `js_sys::JsString` keeps text as a JavaScript handle instead of re-encoding it; - `js_sys::Promise` is the handle an async JavaScript API returns. None of these needs a feature flag: depending on js-sys gives the whole crate. web-sys builds on it, so web-sys signatures name js-sys types (`js_sys::Object` from `get_context`, for example). ## A working feature list The canvas filter below needs five features: `Window` and `Document` to reach the page, `HtmlCanvasElement` and `CanvasRenderingContext2d` for the canvas, and `ImageData` for the pixels. `ImageData::data` returns a Rust-side copy of the pixels, and `new_with_u8_clamped_array_and_sh` builds a new image from them. Habits that save time: - start from the docs line of each method you call and add every feature it names; - treat an E0599 on a web-sys type as a missing feature before suspecting the API; - keep the features list in one crate of the workspace, so the browser bindings stay in one place; - reach for js-sys first when the code only needs JavaScript built-ins, since it has no feature list to maintain.

  • How do you find out which web-sys features a method needs before compiling?
    Read the method's documentation: web-sys appends a line to every binding, for example "This API requires the following crate features to be activated: `Document`, `Window`" on `Window::document`. The source shows the same thing as `#[cfg(feature = "...")]` on the binding. Copy every name into the dependency's `features` list.
  • Why does `canvas.get_context("2d")` need `dyn_into` before you can draw?
    `get_context` returns a generic `Object` handle, because the JavaScript method can return several context types. `dyn_into::<CanvasRenderingContext2d>()` from `JsCast` checks the real type at run time and returns the typed handle, or the original value as an error if it does not match. A Rust `as` cast between these types is rejected at compile time.

  • Adding `web-sys` to `[dependencies]` gives access to the whole DOM API.
  • Enabling the `Window` feature is enough to call every method on `Window`.
  • js-sys is the crate that binds DOM elements such as `HtmlCanvasElement`.
  • A missing web-sys feature shows up as an error in the browser at run time.
  • An `Element` becomes an `HtmlCanvasElement` with a plain `as` cast.