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`.
|
|
|
|
|
2024-09-03 15:16:37 +00:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2024-01-14 04:51:37 +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.
|
2024-02-02 21:09:00 +00:00
|
|
|
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
|
2024-09-03 15:16:37 +00:00
|
|
|
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.
|
2024-01-16 01:04:39 +00:00
|
|
|
let mut eval = eval(
|
2023-10-23 20:26:10 +00:00
|
|
|
r#"
|
2023-07-21 22:36:25 +00:00
|
|
|
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!";
|
2023-07-21 22:36:25 +00:00
|
|
|
"#,
|
2024-02-14 23:13:15 +00:00
|
|
|
);
|
2023-07-21 22:36:25 +00:00
|
|
|
|
2024-02-14 20:33:07 +00:00
|
|
|
// Send a message to the JS code.
|
2023-10-23 20:26:10 +00:00
|
|
|
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".
|
2023-10-23 20:26:10 +00:00
|
|
|
let res = eval.recv().await.unwrap();
|
2024-02-14 20:33:07 +00:00
|
|
|
|
|
|
|
// This will print "Hi from JS!" and "Hi from Rust!".
|
2023-10-23 20:26:10 +00:00
|
|
|
println!("{:?}", eval.await);
|
2024-02-14 20:33:07 +00:00
|
|
|
|
2023-10-23 20:26:10 +00:00
|
|
|
res
|
2023-07-21 22:36:25 +00:00
|
|
|
});
|
|
|
|
|
2024-02-01 09:05:28 +00:00
|
|
|
match future.value().as_ref() {
|
2024-01-16 19:18:46 +00:00
|
|
|
Some(v) => rsx!( p { "{v}" } ),
|
|
|
|
_ => rsx!( p { "waiting.." } ),
|
2023-07-21 22:36:25 +00:00
|
|
|
}
|
2022-03-19 02:11:30 +00:00
|
|
|
}
|