const importObject = {
my_namespace: { imported_func: (arg) => console.log(arg) },
};Using the WebAssembly JavaScript API / notebook
Using the WebAssembly JavaScript API
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
(obj) => obj.instance.exports.exported_func(),
);fetch("simple.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => WebAssembly.instantiate(bytes, importObject))
.then((results) => {
results.instance.exports.exported_func();
}); const memory = new WebAssembly.Memory({ initial: 10, maximum: 100 }); const data = new DataView(memory.buffer);
data.setUint32(0, 42, true); data.getUint32(0, true);memory.grow(1); WebAssembly.instantiateStreaming(fetch("memory.wasm"), {
js: { mem: memory },
}).then((results) => {
// add code here
}); const summands = new DataView(memory.buffer);
for (let i = 0; i < 10; i++) {
summands.setUint32(i * 4, i, true);
}
const sum = results.instance.exports.accumulate(0, 10);
console.log(sum); WebAssembly.instantiateStreaming(fetch("table.wasm")).then((results) => {
// add code here
}); const tbl = results.instance.exports.tbl;
console.log(tbl.get(0)()); // 13
console.log(tbl.get(1)()); // 42const global = new WebAssembly.Global({ value: "i32", mutable: true }, 0);const output = document.getElementById("output");
function assertEq(msg, got, expected) {
const result =
got === expected
? `SUCCESS! Got: ${got}\n`
: `FAIL!\nGot: ${got}\nExpected: ${expected}\n`;
output.innerText += `Testing ${msg}: ${result}`;
}
assertEq("WebAssembly.Global exists", typeof WebAssembly.Global, "function");
const global = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
WebAssembly.instantiateStreaming(fetch("global.wasm"), { js: { global } }).then(
({ instance }) => {
assertEq(
"getting initial value from wasm",
instance.exports.getGlobal(),
0,
);
global.value = 42;
assertEq(
"getting JS-updated value from wasm",
instance.exports.getGlobal(),
42,
);
instance.exports.incGlobal();
assertEq("getting wasm-updated value from JS", global.value, 43);
},
);