🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly Imports: Call JavaScript from Wasm

A WebAssembly import is a JavaScript function or value a module uses. The import section lists each one, and JavaScript supplies it in the import object.

Import a log function

This module imports log from env. Its run function calls log twice.

(module
  (import "env" "log" (func $log (param i32)))
  (func (export "run")
    i32.const 42
    call $log
    i32.const 7
    call $log))

Supply log in JavaScript

The import object has an env group. That group holds a log function.

const { instance } = await WebAssembly.instantiate(bytes, {
  env: {
    log: (value) => console.log(value),
  },
});
instance.exports.run();

Example

(async () => {
  const B64 = "AGFzbQEAAAABCAJgAX8AYAAAAgsBA2VudgNsb2cAAAMCAQEHBwEDcnVuAAEKDAEKAEEqEABBBxAACw==";
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes, {
    env: { log: (value) => console.log(value) },
  });
  instance.exports.run();
})();

Key points

  • An import is a JavaScript value a module uses.
  • The import section names the group and the item.
  • JavaScript supplies each import in the import object.
  • The module and the import object must match entry by entry.
  • A wrong type or a missing entry stops instantiation.

In this example, the bytes are decoded and started with an import object that supplies log. Then run is called. Inside run, Wasm calls the imported log with 42 first and with 7 next. JavaScript prints 42 and then 7.

Note

The module name here is env, the usual group name.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What must the import object do for a module that imports env.log?