From 55c40256545428249ad07bff0336fb7c326771be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sampo=20Kivist=C3=B6?= Date: Tue, 23 Jul 2024 21:03:55 +0300 Subject: [PATCH 1/2] Added an exmple how to use js bindings --- examples/js-binding-listener.rs | 50 +++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 examples/js-binding-listener.rs diff --git a/examples/js-binding-listener.rs b/examples/js-binding-listener.rs new file mode 100644 index 00000000..b5b95237 --- /dev/null +++ b/examples/js-binding-listener.rs @@ -0,0 +1,50 @@ +use std::sync::Arc; +use futures::StreamExt; +use tokio::sync::Mutex; +use chromiumoxide::browser::{Browser, BrowserConfig}; +use chromiumoxide_cdp::cdp::js_protocol::runtime::{AddBindingParams, EventBindingCalled}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + tracing_subscriber::fmt::init(); + + let (mut browser, mut handler) = + Browser::launch(BrowserConfig::builder().with_head().build()?).await?; + + let handle = async_std::task::spawn(async move { + while let Some(h) = handler.next().await { + match h { + Ok(_) => continue, + Err(_) => break, + } + } + }); + + let page = browser.new_page("about:blank").await?; + + let mut listener = page.event_listener::().await?; + + let value_from_js: Arc> = Arc::new(Mutex::new("".to_string())); + let value_from_js_clone = Arc::clone(&value_from_js); + + tokio::spawn(async move { + while let Some(event) = listener.next().await { + if event.name == "testFunc1" { + let mut locked_value = value_from_js_clone.lock().await; + *locked_value = event.payload.clone(); + } + } + }); + + page.execute(AddBindingParams::new("testFunc1")).await?; + + page.evaluate("window.testFunc1('30');").await?; + + let value = value_from_js.lock().await; + assert_eq!(*value, "30"); + + browser.close().await?; + handle.await; + + Ok(()) +} \ No newline at end of file From 938f9c4f7490c0b94f6bcf00f4cfb685fbc358e4 Mon Sep 17 00:00:00 2001 From: Matthias Seitz Date: Tue, 23 Jul 2024 23:00:02 +0200 Subject: [PATCH 2/2] rustmft --- examples/js-binding-listener.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/js-binding-listener.rs b/examples/js-binding-listener.rs index b5b95237..2aaa06a0 100644 --- a/examples/js-binding-listener.rs +++ b/examples/js-binding-listener.rs @@ -1,8 +1,8 @@ -use std::sync::Arc; -use futures::StreamExt; -use tokio::sync::Mutex; use chromiumoxide::browser::{Browser, BrowserConfig}; use chromiumoxide_cdp::cdp::js_protocol::runtime::{AddBindingParams, EventBindingCalled}; +use futures::StreamExt; +use std::sync::Arc; +use tokio::sync::Mutex; #[tokio::main] async fn main() -> Result<(), Box> { @@ -47,4 +47,4 @@ async fn main() -> Result<(), Box> { handle.await; Ok(()) -} \ No newline at end of file +}