Pass JavaScript Functions to WebAssembly Code in the Browser
In this Shortcut, we are going to do something more sophisticated with the communication between JavaScript and a WebAssembly module than we did in “Call WebAssembly Code from JavaScript in the Browser.” In that Shortcut, we called console.log
from JavaScript with the result from executing a WebAssembly function. In this Shortcut, we will call console.log
from WebAssembly itself.
There is only one problem: we can’t do that! WebAssembly has no way of printing to the console or doing other kinds of input/output activity.
Instead, we have to give the WebAssembly module a function to import. At that point, the module can invoke that function, which can call console.log
as usual. This process of sharing a function is done through the importObject
, which is an optional parameter to the instantiateStreaming()
function. We do not need to pass it in if it is not expected, but in this case, the importObject
will be used as part of the module instantiation process. Just as the instance allows us to access exported elements from the module, the module can import elements from its JavaScript host environment. In the GitHub repository for this Shortcut, you should enter the directory 06-Browser
.
As we did in the previous Shortcut, we are going to be using HTML and JavaScript to invoke the behavior in the module. This time, the module definition is in text format in the file
Get Pass JavaScript Functions to WebAssembly Code in the Browser now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.