6

Is it possible to pass javascript callback to WebAssembly? Can we trigger an event from WebAssembly and listen to it in javascript?

2 Answers 2

5

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

Web Client

<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>

Rust prototype

extern "C" {
   fn logit();
}

Rust

#[no_mangle]
pub extern fn add_one(a: u32) -> u32 {
    logit();
    a + 1
}

Credit

All credit goes to Kevin Hoffman's Article

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.