Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add console-log example to show usage of EventConsoleApiCalled to capture console logs #239

Merged
merged 1 commit into from
Sep 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
Loading