Launch and control a browser with chromiumoxide
mainchromiumoxide provides an async API to control Chrome or Chromium via the DevTools Protocol. To use it, you must launch a Browser and spawn a background task to continuously poll the handler which drives the websocket connection.
Key steps:
- Create a
BrowserConfig(e.g., using.with_head()for non-headless mode). - Call
Browser::launch(config)to get aBrowserinstance and ahandler. - Spawn a
tokiotask to pollhandler.next(). - Use
browser.new_page(url)to interact with pages and elements.
use futures::StreamExt;
use chromiumoxide::browser::{Browser, BrowserConfig};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// create a `Browser` that spawns a `chromium` process running with UI (`with_head()`, headless is default)
// and the handler that drives the websocket etc.
let (mut browser, mut handler) =
Browser::launch(BrowserConfig::builder().with_head().build()?).await?;
// spawn a new task that continuously polls the handler
let handle = tokio::spawn(async move {
while let Some(h) = handler.next().await {
if h.is_err() {
break;
}
}
});
// create a new browser page and navigate to the url
let page = browser.new_page("https://en.wikipedia.org").await?;
// find and click the search toggle button to reveal the search bar
page.find_element(".search-toggle").await?.click().await?;
// find the search bar type into the search field and hit `Enter`,
// this triggers a new navigation to the search result page
page.find_element("input[name='search']")
.await?
.click()
.await?
.type_str("Rust programming language")
.await?
.press_key("Enter")
.await?;
let html = page.wait_for_navigation().await?.content().await?;
browser.close().await?;
handle.await?;
Ok(())
}