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>
Calling JavaScript from Rust in WASM lets your high-performance Rust code run inside a web browser and talk to JavaScript. You mark a Rust function to be visible to the web, then call it just like any other JavaScript function. Think of it as a bridge where Rust does the heavy lifting and JavaScript handles the user interface.