Is it possible to pass javascript callback to WebAssembly? Can we trigger an event from WebAssembly and listen to it in javascript?
I found this article from Kevin Hoffman attempting this using rust.
It boils down to using WebAssembly.instantiate(bufferSource, importObject) optional importObject. You can read more about this on MDN.
Here is the example for the article
<html>
<head>
<script>
function logit() {
console.log('this was invoked by Rust, written in JS');
}
let imports = {logit};
fetch('wasm_project.gc.wasm')
.then(r => r.arrayBuffer() )
.then(r => WebAssembly.instantiate(r, { env: imports }))
.then(wasm_module => {
alert(`2 + 1 = ${wasm_module.instance.exports.add_one(2)}`);
});
</script>
</head>
<body></body>
</html>
extern "C" {
fn logit();
}
#[no_mangle]
pub extern fn add_one(a: u32) -> u32 {
logit();
a + 1
}
All credit goes to Kevin Hoffman's Article
You can, but you have to use a function table from the webassembly side. What it does its just referencing functions by index in a table and calling them with a dynamic index using call_indirect.
Note: The table is a core thing of webassembly but I don't know how it is implemented in other languages other than WebAssembly-Text (wat). The call_indirect is the binary instruction's name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With