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 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 succesffully 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. .unwrap();
  26. // Send a message to the JS code.
  27. eval.send("Hi from Rust!".into()).unwrap();
  28. // Our line on the JS side will log the message and then return "hello world".
  29. let res = 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. }