Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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

    Nik GrafNik Graf

    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.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: 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.

    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.

    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.

    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.