How to Call JavaScript from Rust in WASM

Web
Export Rust functions with wasm_bindgen and call them directly from JavaScript in the browser.

You call JavaScript from Rust in WASM by exporting a Rust function with #[wasm_bindgen] and invoking it via window in the browser.

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}
<script>
  import init, { greet } from './pkg/my_wasm.js';
  init().then(() => {
    console.log(greet('World'));
  });
</script>