6

I am trying to work out how to call a JavaScript function using Rust and wasm-bindgen. Due to lack of browser support, I cannot use wasm-bindgen with ES6 modules together with a Web Worker.

As far as I can tell, declaring that a JavaScript function exists for me to call on the Rust side is straightforward

#[wasm_bindgen]
extern {
    fn logProgress(percent: f64);
}

I have no idea where to define the JavaScript implementation however. If I try to just call a Rust function from JavaScript that calls the undefined logProgress then I get a runtime error: Error: logProgress is not defined

I can see from the wasm-bindgen docs that if I was using wasm-bindgen with ES6 modules then I could change the rust code to

#[wasm_bindgen(module = "/progress.js")]
extern {
    fn logProgress(percent: f64);
}

and declare the JavaScript function in progress.js

export function logProgress(percent) {
    console.log(percent)
    // actual implementation would not just log
}

Since I am instead importing my Rust APIs via the wasm_bindgen global, I presume I should be able to define the implementation somewhere around the same part in my Web Worker, but I have searched through a lot of docs and can't find anything on how to do this.

importScripts('foo_wasm.js')
wasm_bindgen('foo_wasm_bg.wasm').then(fooWasmModule => {
    memory = fooWasmModule.memory
    const { Foo, Bar, Baz, foobar } = wasm_bindgen;
    // JS has 'imported' the Rust structs and functions
    // How to 'export' the JS functions to Rust?
}
Skeletonxf
  • 341
  • 2
  • 7
  • 1
    wasm_bindgen will be binding that import to `logProgress` in the [`WorkerGlobalScope`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope) (per [`importScripts`](https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/importScripts)—there's nothing special about bindgen here). Either define the function in the worker's global namespace, e.g. at the same level as the `importScripts` call, or import it too from a file using another `importScripts` call (or another argument to the same call). If you want to use a non-global namespace, set the `js_namespace`. – eggyal Sep 08 '20 at 10:43

0 Answers0