4

In my javascript, before calling wasm, I define a function jalert that I later want to call from Rust using wasm. I couldn't find in the documentation for wasm-bindgen how to call an arbitrary function that I previously defined in javascript as below. I got functions like alert and console.log to work, because they are already part of javascript, but I couldn't have this function jalert to work. I get an error in the browser, saying that it is not defined. With the alert function, it doesn't complain.

    function jalert(sometext) {
        alert(sometext);
    }
    
    jalert("I am Claudio");
    
    // This works from Javascript

In the Rust file lib.rs:

    #[wasm_bindgen]
    extern "C" {
        fn alert(s: &str);
        fn jalert(s: &str);
    }
    
    #[wasm_bindgen]
    pub fn run_alert(item: &str) {
        jalert(&format!("This is WASM calling javascript function jalert and {}", item));
        alert(&format!("This is WASM and {}", item));
    }
    
// The alert() code works fine. The jalert() call in run_alert() gives me a browser error that jalert is not defined

Jmb
  • 18,893
  • 2
  • 28
  • 55

1 Answers1

0

I'd say you need to add #wasm_bindgen to your method declaration:

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(method, js_name = alert]
    fn alert(s: &str);
    #[wasm_bindgen(method, js_name = jalert]
    fn jalert(s: &str);
}
Michael
  • 2,528
  • 3
  • 21
  • 54
  • Thank you Michael. I still get the same error message after these modifications: Uncaught (in promise) ReferenceError: jalert is not defined at imports.wbg.__wbg_jalert_6ea7bc7bf4379211 (wa.js:161) at run_alert (/pkg/wa_bg.wasm:wasm-function[25]:0x3adf) at runWasm (index.js:20) – Claudio Soprano Jul 16 '20 at 15:22
  • 1
    You could try to use web-sys crate to call window.alert or window.jalert instead. It provides a wrapper for the Javascript context and its objects and functions. – Michael Jul 17 '20 at 16:14