Skip to main content

playwright_cdp/
browser_type.rs

1//! `BrowserType` — a browser engine entry point (Playwright-shaped).
2//!
3//! Unlike upstream Playwright, this crate drives Chromium directly over CDP
4//! and does **not** spawn a Node.js driver. `BrowserType` is therefore a thin
5//! handle whose only real engine is Chromium; `firefox()`/`webkit()` exist for
6//! API shape parity and resolve to Chromium (with a warning).
7
8use crate::browser::Browser;
9use crate::browser_process;
10use crate::error::Result;
11use crate::options::{ConnectOverCdpOptions, LaunchOptions};
12use std::path::PathBuf;
13
14/// Which browser engine a [`BrowserType`] represents.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Engine {
17    Chromium,
18    Firefox,
19    Webkit,
20}
21
22/// A browser engine. Created from a [`Playwright`](crate::Playwright) handle.
23#[derive(Debug, Clone, Copy)]
24pub struct BrowserType {
25    engine: Engine,
26}
27
28impl BrowserType {
29    pub(crate) fn new(engine: Engine) -> Self {
30        Self { engine }
31    }
32
33    /// Chromium engine (the only fully-supported engine here).
34    pub fn chromium() -> Self {
35        Self::new(Engine::Chromium)
36    }
37
38    /// Engine name: `"chromium"`, `"firefox"`, or `"webkit"`.
39    pub fn name(&self) -> &'static str {
40        match self.engine {
41            Engine::Chromium => "chromium",
42            Engine::Firefox => "firefox",
43            Engine::Webkit => "webkit",
44        }
45    }
46
47    /// Best-effort discovery of the executable path for this engine.
48    pub fn executable_path(&self) -> Option<PathBuf> {
49        browser_process::discover_executable(&LaunchOptions::default()).ok()
50    }
51
52    /// Launch a browser with default options.
53    pub async fn launch(&self) -> Result<Browser> {
54        self.launch_with_options(LaunchOptions::default()).await
55    }
56
57    /// Launch a browser with the given options.
58    ///
59    /// Only Chromium is driven here; `firefox`/`webkit` log a warning and fall
60    /// back to launching Chromium (kept for porting compatibility).
61    pub async fn launch_with_options(&self, opts: LaunchOptions) -> Result<Browser> {
62        if !matches!(self.engine, Engine::Chromium) {
63            tracing::warn!(
64                engine = self.name(),
65                "playwright-cdp only drives Chromium via CDP; launching Chromium instead"
66            );
67        }
68        Browser::launch(opts).await
69    }
70
71    /// Attach to an already-running browser over CDP.
72    pub async fn connect_over_cdp(
73        &self,
74        endpoint: &str,
75        opts: Option<ConnectOverCdpOptions>,
76    ) -> Result<Browser> {
77        Browser::connect_over_cdp(endpoint, opts).await
78    }
79}