web-sys is a crate, a library in Rust, that contains Raw API bindings for Web APIs. For example, if you need to use the "Window.console.log" function (browser's debugging console) in rustwasm, one way to do this is, you can define define the bindings for this WEB API using "wasm-bindgen". Alternatively, you can save some work on the definition by simply making use of web_sys. To use an API in web_sys, you will just need to enable the features for the types used in the API.
The Cargo.toml below enables the use of the "Window" object and also other useful Web APIs objects (or Structs in Rust) such as "Document" or "HtmlElement".
Cargo.toml
[package]
name = "dom"
version = "0.1.0"
authors = ["www.webassemblyman.com"]
edition = "2019"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.50"
[dependencies.web-sys]
version = "0.3.4"
features = [
'Document',
'Element',
'HtmlElement',
'Node',
'Window',
]
After enabling the features of the Web APIs in web_sys, you can easily use them in your rustwasm programs as shown below. The exanple below illustrates how to add a <p> element to the Document Object Model (DOM).
src/lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen(start)]
pub fn run() -> Result<(), JsValue> {
let window = web_sys::window().expect("no window exists");
let document = window.document().expect("window should have a document");
let body = document.body().expect("document should have a body");
let val = document.create_element("p")?;
val.set_inner_html("Hello World from webassemblyMan!");
body.append_child(&val)?;
Ok(())
}