Access JS Functions and Variables from a Go WebAssembly Program

Xiaoru Li
InstructorXiaoru Li

Share this video with your friends

Send Tweet
Published 3 years ago
Updated 2 years ago

Go ^1.12

In this lesson, we will see how we can interact with the JavaScript environment by using Go's syscall/js module to call and pass values into a JavaScript function, and access variables available in JS land.

Xiaoru Li: [0:01] Here, we have a JavaScript file loaded before the web assembly binary is initialized. There are a few functions and variables in the file which we'll interact with from our Go code.

[0:15] In our Go code, let's first import the syscall/js module. Then, we can use js.Global() function, so we are able to access variables and functions in the JavaScript land.

[0:29] Now let's access the add() function in the global scope. When the target we want to access is a function, we need to chain a .Call to the parent, which in this case is js.global. Then, we pass in first the name of the function, then all the parameters for the function in the correct order. Now we can access the return value.

[0:51] Because we expect the return value of the add function to be a JavaScript number, which is a float in Go, we'll need to call .Float() to convert it back to Go land's building type. Of course, we can also truncate the number into an integer by calling Int().

[1:13] Following the same logic, we can also call this hello() function which returns a String(). The .Get() method allows us to access properties on an object, which means that we can access the global variables env and the config as well. Notice now we're using var instead of let here in the JavaScript snippet because let is not globally scoped. Let's print the env variable to the console as well.

[1:53] To assign new values to properties, we can use .Set(). This way, we can update the value of this env variable to DEV by calling Set, then pass in the variable name env and a value DEV. We can check the updates in the console.

[2:14] We can also do nested calls to insert a new property to the config object by calling .Get() to access the object first, then .Set() to create a new property.

[2:29] Everything works in the browser.