#[cfg(feature = "headless")]
pub use headless_impl::ManagedTab;
#[cfg(not(feature = "headless"))]
pub struct ManagedTab;
#[cfg(feature = "headless")]
mod headless_impl {
use anyhow::Context as _;
use chromiumoxide::Page;
use std::time::Duration;
pub struct ManagedTab {
pub(crate) page: Page,
_permit: tokio::sync::OwnedSemaphorePermit,
}
impl ManagedTab {
pub(crate) fn new(page: Page, permit: tokio::sync::OwnedSemaphorePermit) -> Self {
Self {
page,
_permit: permit,
}
}
pub async fn navigate(&self, url: &str, timeout_ms: u64) -> anyhow::Result<()> {
tokio::time::timeout(Duration::from_millis(timeout_ms), self.page.goto(url))
.await
.context("Navigation timed out")?
.context("Navigation failed")?;
Ok(())
}
pub async fn navigate_and_wait(
&self,
url: &str,
selector: &str,
timeout_ms: u64,
) -> anyhow::Result<()> {
tokio::time::timeout(Duration::from_millis(timeout_ms), self.page.goto(url))
.await
.context("Navigation timed out")?
.context("Navigation failed")?;
let wait_result = tokio::time::timeout(
Duration::from_millis(timeout_ms / 2),
self.page.find_element(selector),
)
.await;
if wait_result.is_err() {
tracing::debug!(
"navigate_and_wait: selector {selector:?} not found within timeout"
);
}
Ok(())
}
pub async fn content(&self) -> anyhow::Result<String> {
self.page
.content()
.await
.context("Failed to get page content")
}
pub async fn evaluate(&self, expression: &str) -> anyhow::Result<String> {
let result = self
.page
.evaluate(expression)
.await
.context("JS evaluation failed")?;
Ok(format!("{:?}", result.value()))
}
pub fn page(&self) -> &Page {
&self.page
}
}
}