A module cannot do anything alone
Pure WebAssembly can add, loop and store bytes, but it cannot print, fetch a page, draw on a canvas or read the clock. Those powers belong to the host. A module that wants one declares an import, a name it expects someone else to supply, and the host provides a matching value when the module is instantiated.
That is a security feature as much as a convenience. The module can only touch what you hand it through the import object. If you give it no network function, it simply has no way to reach the network, however its code was written.
The import object
Each import has a two-part name: a module name and a field name, such as env and log. In JavaScript you pass an object shaped the same way as the second argument to new WebAssembly.Instance(module, imports). Wasm functions can only exchange numbers, so an imported function receives and returns numbers.
function listImports(bytes) {
const module = new WebAssembly.Module(bytes);
return WebAssembly.Module.imports(module).map((i) => `${i.module}.${i.name} (${i.kind})`);
}
function run(x, factor) {
const logged = [];
const imports = {
env: {
log: (n) => logged.push(n), // wasm calls back into JavaScript
scale: (n) => n * factor,
},
};
const { run } = new WebAssembly.Instance(new WebAssembly.Module(IMPORT_WASM), imports).exports;
return { result: run(x), logged };
}
function linkError(imports) {
try {
new WebAssembly.Instance(new WebAssembly.Module(IMPORT_WASM), imports);
return "ok";
} catch (e) {
return e.name;
}
}WebAssembly.Module.imports(module) lists what a module needs. Run it first when a third-party .wasm file refuses to load.