Search code examples
javascriptwebassemblyevent-driven

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?


Solution

  • 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