使用 web-sys

web-sys 作为依赖项添加到你的 Cargo.toml 文件中

[dependencies]
wasm-bindgen = "0.2"

[dependencies.web-sys]
version = "0.3"
features = [
]

为你正在使用的 API 启用 cargo 特性

为了保持构建速度超快,web-sys 将每个 Web 接口都放在 cargo 特性后面。在 API 文档中查找你要使用的类型或方法;它将列出访问该 API 必须启用的特性。

例如,如果我们正在查找 window.resizeTo 函数,我们将在 API 文档中搜索 resizeTo。我们将找到 web_sys::Window::resize_to 函数,它需要 Window 特性。为了访问该函数,我们在 Cargo.toml 中启用 Window 特性

[dependencies.web-sys]
version = "0.3"
features = [
  "Window"
]

调用该方法!

#![allow(unused)]
fn main() {
use wasm_bindgen::prelude::*;
use web_sys::Window;

#[wasm_bindgen]
pub fn make_the_window_small() {
    // Resize the window to 500px by 500px.
    let window = web_sys::window().unwrap();
    window.resize_to(500, 500)
        .expect("could not resize the window");
}
}