Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can WebAssembly get javascript callback?

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

like image 501
Shula Avatar asked Mar 04 '19 14:03

Shula


Video Answer


2 Answers

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

like image 112
Michael Warner Avatar answered Sep 30 '22 03:09

Michael Warner


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

like image 32
faBri_CI-o Avatar answered Sep 30 '22 04:09

faBri_CI-o