12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
15 : 06 : 04 : 56
Become a member
to unlock all features

    Pass a JavaScript Function to WebAssembly and Invoke it from Rust

    Nik GrafNik Graf

    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.



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

    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.

    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.

    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.

    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.

    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.