5 Creating a WebAssembly module that calls into JavaScript
This chapter covers:
- Calling into JavaScript directly using Emscripten’s toolkit
- Calling into JavaScript without Emscripten’s toolkit
In chapter 4, you created a WebAssembly module where your JavaScript code called into it by using Emscripten’s ccall helper function. You passed a buffer as a parameter to the module’s function so that, if there was an issue, an error message could be returned by placing it into the buffer. If there was an issue, your JavaScript read the string from the module’s memory and then displayed the message to the user, as shown in figure 5.1.
Figure 5.1 The way the JavaScript code is interacting currently with the module’s functions

Imagine that rather than passing a buffer to the module’s function if there’s an issue, the module can just pass the error message directly to your JavaScript as shown in figure 5.2.
Figure 5.2 The module calling a function in the JavaScript code.

When using the Emscripten toolkit, there are three ways that you can interact with JavaScript code from your module: