Calling the JavaScript API via WebAssembly

Learn how to call JavaScript API using WebAssembly.

JavaScript provides a rich API to work with objects, arrays, maps, sets, and so on. If we want to use or define them in Rust, then we need to provide the necessary bindings. Handcrafting those bindings will be a huge process. But what if we have bindings to those APIs? There’s a common API for both Node.js and a browser environment that will create a platform where we can write the code completely in Rust and use wasm_bindgen to create necessary code.

The RustWASM team’s answer to that is the js-sys crate.

The js-sys crate contains raw #[wasm_bindgen] bindings to all the global APIs guaranteed to exist in every JavaScript environment by the ECMAScript standard—RustWASM.

They provide bindings to JavaScript’s standard built-in objects, including their methods and properties.

Getting started with the project

In this example, let’s see how to call a JavaScript API via WebAssembly:

  1. Create a default project with the cargo new command:

Get hands-on with 1200+ tech skills courses.