Skip to content

Commit

Permalink
add console-log example (#239)
Browse files Browse the repository at this point in the history
  • Loading branch information
tgrushka authored Sep 21, 2024
1 parent 6727f0f commit 07ee966
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ required-features = ["tokio-runtime", "tokio"]
name = "storage-cookie"
required-features = ["tokio-runtime"]

[[example]]
name = "console-logs"
required-features = ["tokio-runtime"]

[[example]]
name = "httpfuture"
Expand Down
53 changes: 53 additions & 0 deletions examples/console-logs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// This example demonstrates how to capture console logs.

use std::time::Duration;

use chromiumoxide::{cdp::js_protocol::runtime::EventConsoleApiCalled, BrowserConfig};
use futures::StreamExt;

const TARGET: &str = "https://www.microsoft.com/";

#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();

let (mut browser, mut handler) =
chromiumoxide::Browser::launch(BrowserConfig::builder().with_head().build().unwrap())
.await
.expect("failed to launch browser");

let handle = tokio::task::spawn(async move {
while let Some(event) = handler.next().await {
tracing::debug!(event = ?event);
}
});

let page = browser
.new_page("about:blank")
.await
.expect("failed to create page");

let mut console_events = page
.event_listener::<EventConsoleApiCalled>()
.await
.expect("Failed to add event listener");
let logs_handle = tokio::spawn(async move {
while let Some(event) = console_events.next().await {
println!(
"{}",
serde_json::to_string_pretty(&*event).expect("Failed to serialize event")
);
}
});

let _ = page.goto(TARGET).await.expect("failed to navigate");

tokio::time::sleep(Duration::from_secs(3)).await;

browser.close().await.expect("Failed to close browser");
logs_handle.await.expect("Failed to wait for logs handle");
handle.await.expect("Failed to await handle");

// Give browser time to finish closing.
tokio::time::sleep(Duration::from_secs(1)).await;
}

0 comments on commit 07ee966

Please sign in to comment.