Use the js-sys Crate to Invoke Global APIs Available in Any JavaScript Environment

Nik Graf
InstructorNik Graf
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 6 years ago

js-sys offers bindings to all the global APIs available in every JavaScript environment as defined by the ECMAScript standard.

In this lesson, we will install and use js-sys to invoke JavaScript's Date API to grab the current time. The date will need to be converted to a value Rust can use and display that date from Rust in the browser.

Instructor: [00:00] In this lesson, we start out with a fresh Rust webpack template. Then we add the js-sys dependency to our Cargo.toml. In our Rust file, we declare that we use js-sys, and now, this allows us to use Javascript APIs inside Rust.

[00:19] The example I want to show is updating the welcome message by displaying the current time at the end. We first create a new timestamp, represented as a float using Javascript Date.now function. Next up, we create the new date based on this float value.

[00:42] This data object has multiple methods that we label, like getHours and getMinutes. That's great, because we can leverage them to do some string interpolation, and generate our welcome message. We switch over to the browser and check our results.

[01:01] As expected, we see "Hello from Rust," including the current time. Isn't it amazing, with almost no effort, we can access Javascript APIs from Rust? This not only works in the browser, but also in Node.