dioxus/examples/eval.rs

48 lines
1.7 KiB
Rust
Raw Normal View History

2024-02-14 20:33:07 +00:00
//! This example shows how to use the `eval` function to run JavaScript code in the webview.
//!
//! Eval will only work with renderers that support javascript - so currently only the web and desktop/mobile renderers
//! that use a webview. Native renderers will throw "unsupported" errors when calling `eval`.
use async_std::task::sleep;
2022-03-19 02:11:30 +00:00
use dioxus::prelude::*;
fn main() {
2024-01-20 08:11:55 +00:00
launch(app);
2022-03-19 02:11:30 +00:00
}
fn app() -> Element {
2024-03-31 15:24:24 +00:00
// Create a future that will resolve once the javascript has been successfully executed.
let future = use_resource(move || async move {
2024-02-14 20:33:07 +00:00
// Wait a little bit just to give the appearance of a loading screen
sleep(std::time::Duration::from_secs(1)).await;
2024-02-14 20:33:07 +00:00
// The `eval` is available in the prelude - and simply takes a block of JS.
// Dioxus' eval is interesting since it allows sending messages to and from the JS code using the `await dioxus.recv()`
// builtin function. This allows you to create a two-way communication channel between Rust and JS.
let mut eval = eval(
r#"
dioxus.send("Hi from JS!");
let msg = await dioxus.recv();
console.log(msg);
2024-02-14 20:33:07 +00:00
return "hi from JS!";
"#,
);
2024-02-14 20:33:07 +00:00
// Send a message to the JS code.
eval.send("Hi from Rust!".into()).unwrap();
2024-02-14 20:33:07 +00:00
// Our line on the JS side will log the message and then return "hello world".
let res = eval.recv().await.unwrap();
2024-02-14 20:33:07 +00:00
// This will print "Hi from JS!" and "Hi from Rust!".
println!("{:?}", eval.await);
2024-02-14 20:33:07 +00:00
res
});
match future.value().as_ref() {
2024-01-16 19:18:46 +00:00
Some(v) => rsx!( p { "{v}" } ),
_ => rsx!( p { "waiting.." } ),
}
2022-03-19 02:11:30 +00:00
}