Call a Go WebAssembly function from JavaScript

Xiaoru Li
InstructorXiaoru Li

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

Go ^1.12

In this lesson, we will see how we can expose Go lang functions from a WebAssembly module so that we can interact with them from the JavaScript environment.

Xiaoru Li: [0:00] Here is a simple add() function written in standard Go language. To make this Go function available to JavaScript, first we need to attach it to the Global object by using the syscall/js module.

[0:15] In a main() function we write js.Globa() then set the property name "add" on a Global object to js.FuncOf(add) which acts as a wrapper around our Go function. As we can see, the wrapper function expects a specific function signature, so the next step for us is to refactor the add function.

[0:41] Every function that we want to expose to JavaScript should take in two arguments. The first one is the this object of the JavaScript execution context of the function, which we can ignore in most cases. The second one is an array of the actual parameters that we want to pass into the function. In our case, we need to replace a and b with inputs and inputs .

[1:06] Now we need to use the .Float() method to convert the js.Value to Go values, so we can compute the sum here. The final step is to change the return type of the function to an empty interface. We can think of this as the any type in TypeScript.

[1:24] Another thing to keep in mind is that Go WebAssemblies are different than Rust or other languages because the binaries are programs that runs for once they exit, instead of being like a static library.

[1:37] Here we need to prevent the program to exit by creating an open channel. Then we can make the program listen to the channel at the end of the main() function. Because we never send anything to the channel, the Go program will pause the execution so the functions and resources that we have made available for the JavaScript land will be kept intact.

[2:00] Now let's compile and test this in the browser console. Here we go. We can access the Go function from JavaScript now.