eval.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 async_std::task::sleep;
  6. use dioxus::prelude::*;
  7. fn main() {
  8. dioxus::launch(app);
  9. }
  10. fn app() -> Element {
  11. // Create a future that will resolve once the javascript has been successfully executed.
  12. let future = use_resource(move || async move {
  13. // Wait a little bit just to give the appearance of a loading screen
  14. sleep(std::time::Duration::from_secs(1)).await;
  15. // The `eval` is available in the prelude - and simply takes a block of JS.
  16. // Dioxus' eval is interesting since it allows sending messages to and from the JS code using the `await dioxus.recv()`
  17. // builtin function. This allows you to create a two-way communication channel between Rust and JS.
  18. let mut eval = document::eval(
  19. r#"
  20. dioxus.send("Hi from JS!");
  21. let msg = await dioxus.recv();
  22. console.log(msg);
  23. return "hi from JS!";
  24. "#,
  25. );
  26. // Send a message to the JS code.
  27. eval.send("Hi from Rust!").unwrap();
  28. // Our line on the JS side will log the message and then return "hello world".
  29. let res: String = eval.recv().await.unwrap();
  30. // This will print "Hi from JS!" and "Hi from Rust!".
  31. println!("{:?}", eval.await);
  32. res
  33. });
  34. match future.value().as_ref() {
  35. Some(v) => rsx!( p { "{v}" } ),
  36. _ => rsx!( p { "waiting.." } ),
  37. }
  38. }