1
0

eval.rs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. //! This example shows how to use the `eval` function to run JavaScript code in the webview.
  2. //!
  3. //! Eval will only work with renderers that support javascript - so currently only the web and desktop/mobile renderers
  4. //! that use a webview. Native renderers will throw "unsupported" errors when calling `eval`.
  5. use dioxus::prelude::*;
  6. fn main() {
  7. launch(app);
  8. }
  9. fn app() -> Element {
  10. // Create a future that will resolve once the javascript has been successfully executed.
  11. let future = use_resource(move || async move {
  12. // Wait a little bit just to give the appearance of a loading screen
  13. tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
  14. // The `eval` is available in the prelude - and simply takes a block of JS.
  15. // Dioxus' eval is interesting since it allows sending messages to and from the JS code using the `await dioxus.recv()`
  16. // builtin function. This allows you to create a two-way communication channel between Rust and JS.
  17. let mut eval = eval(
  18. r#"
  19. dioxus.send("Hi from JS!");
  20. let msg = await dioxus.recv();
  21. console.log(msg);
  22. return "hi from JS!";
  23. "#,
  24. );
  25. // Send a message to the JS code.
  26. eval.send("Hi from Rust!".into()).unwrap();
  27. // Our line on the JS side will log the message and then return "hello world".
  28. let res = eval.recv().await.unwrap();
  29. // This will print "Hi from JS!" and "Hi from Rust!".
  30. println!("{:?}", eval.await);
  31. res
  32. });
  33. match future.value().as_ref() {
  34. Some(v) => rsx!( p { "{v}" } ),
  35. _ => rsx!( p { "waiting.." } ),
  36. }
  37. }