1×
Become a member
to unlock all features

Level Up!

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

Autoplay

    Pass a JavaScript Function to WebAssembly and Invoke it from Rust

    Nik GrafNik Graf
    rustRust
    javascriptJavaScript

    In some cases it’s useful to be able to invoke a JavaScript function inside Rust. This session showcases how this can be done, by passing along our JavaScript functions to the WebAssembly module instantiation.

    Code

    Code

    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
    Transcript

    Transcript

    Instructor: 00:00 In this lesson, we want to invoke a JavaScript function from our Rust code. First, create the function appendNumberToBody. It accepts a number, creates a text node with the number as its content, and appends the text node to the DOM.

    00:15 When instantiating your WebAssembly module, we can pass along an object which contains the functions to be passed to the module inside the end property. We leverage this to provide our function to the WebAssembly module.

    00:30 Then we switch over to our Rust code. There, we also have to declare which function we want to use. In our case, that's appendNumberToBody. The parameter of the function should be an unsigned integer.

    00:45 Now we need to use appendNumberToBody. Therefore, we export the function run. Inside run, we invoke appendNumberToBody. Note that we have to wrap it with an unsafe block, since the Rust compiler can't provide memory safety guarantees for external functions.

    01:03 Now that we implemented the run function, we also need to invoke it from JavaScript. Then we compile the Rust code, run the HTTP server, and visit our index.html. Fantastic. As you can see, the number 42 was added to our document. Our function to add the number to the DOM came from JavaScript, but it was invoked with the value 42 inside Rust.

    01:32 Let's add one more. In this case, we'll pass the native function inaudible to our module. We import the function, invoke it inside of our unsafe block. Then we recompile and reload the page in our browser. Great. This even works with native browser functions, since we can see the inaudible dialogue.

    Discuss

    Discuss