### Basic Playwright Launch Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.1-protocol-foundation.md Demonstrates how to launch Playwright and access browser types. Ensure Playwright is installed and the driver is downloaded. ```rust use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), Box> { let playwright = Playwright::launch().await?; println!("Playwright launched successfully!"); println!("Chromium: {:?}", playwright.chromium()); Ok(()) } ``` -------------------------------- ### Run Example Project Source: https://github.com/padamson/playwright-rust/blob/main/CLAUDE.md Execute a specific example project, such as 'basic', from the `playwright-rs` package. ```bash cargo run --package playwright-rs --example basic ``` -------------------------------- ### Browser Lifecycle Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.2-browser-api.md Example demonstrating the basic lifecycle of browser, context, and page objects, including creation and closing. ```rust use playwright::Browser; #[tokio::main] async fn main() -> Result<(), Box> { // Launch browser let browser = Browser::launch(Default::default()).await?; // Create a new browser context let context = browser.new_context().await?; // Create a new page within the context let page = context.new_page().await?; // Get the URL of the page (will be "about:blank" in v0.2) println!("Page URL: {}", page.url().await?); // Close the page page.close().await?; // Close the context context.close().await?; // Close the browser browser.close().await?; Ok(()) } ``` -------------------------------- ### Basic Playwright Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.2-browser-api.md A basic example demonstrating the usage of Playwright, including launching a browser, creating a context and page, and performing a simple action like getting the URL. ```rust use playwright::Browser; #[tokio::main] async fn main() -> Result<(), Box> { let browser = Browser::launch(Default::default()).await?; let context = browser.new_context().await?; let page = context.new_page().await?; println!("Page URL: {}", page.url().await?); // Close resources page.close().await?; context.close().await?; browser.close().await?; Ok(()) } ``` -------------------------------- ### Programmatic Browser Installation Source: https://context7.com/padamson/playwright-rust/llms.txt Demonstrates how to programmatically install Playwright browsers using the `install_browsers` function. This is an alternative to using the command-line interface. ```APIDOC ## Programmatic Browser Installation ### Description Installs Playwright browsers programmatically. You can install all browsers or specify a list of browsers to install. ### Usage ```rust use playwright_rs::install_browsers; // Install all browsers install_browsers(None).await?; // Install specific browsers (e.g., chromium) install_browsers(Some(&["chromium"])).await?; ``` ``` -------------------------------- ### Criterion Benchmark Group Setup Source: https://github.com/padamson/playwright-rust/blob/main/docs/benchmarking.md Example of how to set up a benchmark group using criterion.rs in Rust. This defines a group named 'guid_operations' and adds a specific benchmark function 'string_clone' to it. ```rust fn benchmark_guid_string_operations(c: &mut Criterion) { let mut group = c.benchmark_group("guid_operations"); group.bench_function("string_clone", |b| { // benchmark code }); group.finish(); } ``` -------------------------------- ### Running Playwright Rust Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/technical/v0.1-technical-summary.md Command to compile and run the basic Playwright Rust example. The Playwright driver is automatically downloaded by build.rs. ```bash # Driver is auto-downloaded by build.rs into $OUT_DIR; no path setup needed. cargo run --package playwright-rs --example basic ``` -------------------------------- ### Install Playwright Browsers Source: https://context7.com/padamson/playwright-rust/llms.txt Installs the necessary Playwright browsers. This is a prerequisite before running automated tests. Use the npx command or the Rust CLI. ```bash # Install browsers (required before first run) npx playwright@1.59.1 install chromium firefox webkit # Or use the Rust CLI (feature = "cli") cargo install playwright-rs --features cli playwright-rs install chromium firefox webkit ``` -------------------------------- ### Programmatic Browser Installation (Rust) Source: https://github.com/padamson/playwright-rust/blob/main/README.md Installs Playwright browsers directly from Rust code, suitable for setup scripts or Docker images. Requires an async runtime like tokio. ```rust use playwright_rs::install_browsers; install_browsers(None).await?; // all browsers install_browsers(Some(&["chromium"])).await?; // specific browsers ``` -------------------------------- ### Programmatic Browser Installation Source: https://context7.com/padamson/playwright-rust/llms.txt Programmatically install Playwright browsers using the `install_browsers` function. You can install all browsers or specify a subset. ```rust // Programmatic browser installation use playwright_rs::install_browsers; install_browsers(None).await?; // all browsers install_browsers(Some(&["chromium"])).await?; // specific browser ``` -------------------------------- ### Install Playwright Browsers (CLI) Source: https://github.com/padamson/playwright-rust/blob/main/README.md Installs all Playwright browsers or specific ones using the command line. This is a prerequisite for running tests. ```bash npx playwright@1.59.1 install # Or install specific browsers npx playwright@1.59.1 install chromium firefox webkit ``` -------------------------------- ### Network Route Mocking Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.5-advanced-testing.md Shows how to use `page.route()` to intercept network requests. This example demonstrates matching by URL patterns and fulfilling the request. ```rust page.route("**/*.css", |route, _request| route.fulfill(Response::new(200, "text/plain", Some(b"body"))) ) ``` -------------------------------- ### Generate and Open Library Documentation Source: https://github.com/padamson/playwright-rust/blob/main/docs/templates/TEMPLATE_IMPLEMENTATION_PLAN.md Generate documentation for the library, including examples, and automatically open it in a web browser. This is a crucial step for completing library documentation. ```bash cargo doc --open ``` -------------------------------- ### Build Playwright-Rust from Source Source: https://github.com/padamson/playwright-rust/blob/main/README.md Steps to clone the repository, set up pre-commit hooks, and build the project from source. Ensure Node.js and Rust are installed. ```bash # Clone repository git clone https://github.com/YOUR_USERNAME/playwright-rust.git cd playwright-rust # Install pre-commit hooks pip install pre-commit pre-commit install # Build cargo build ``` -------------------------------- ### Custom Implementation Code Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/templates/TEMPLATE_ADR.md A placeholder for a custom implementation code example. This snippet would be replaced with specific code relevant to a unique approach. ```rust // Example showing API usage ``` -------------------------------- ### CLI Bootstrap Installer in Playwright Rust Source: https://github.com/padamson/playwright-rust/blob/main/docs/roadmap.md Describes the new [[bin]] target (feature cli) for the playwright-rs crate, which provides a bootstrap installer for the bundled driver. This facilitates easier distribution and installation via `cargo install`. ```rust [[bin]] ``` -------------------------------- ### Install Playwright Browsers (CI/CD) Source: https://github.com/padamson/playwright-rust/blob/main/README.md Adds Playwright browser installation to a GitHub Actions workflow. Ensure this step runs before tests that require browsers. ```yaml - name: Install Playwright Browsers run: npx playwright@1.59.1 install chromium firefox webkit --with-deps ``` -------------------------------- ### User Code Example with Single-Crate Playwright Source: https://github.com/padamson/playwright-rust/blob/main/docs/adr/0003-single-crate-architecture.md Shows how a user would interact with the Playwright library when it's structured as a single crate. This example is identical to previous versions, highlighting the seamless user experience. ```rust // User code - same as before use playwright::{Playwright, expect}; #[tokio::main] async fn main() -> Result<(), Box> { let playwright = Playwright::initialize().await?; let browser = playwright.chromium().launch().await?; let page = browser.new_page().await?; page.goto("https://example.com", None).await?; expect(page.locator("h1")).to_be_visible().await?; Ok(()) } ``` -------------------------------- ### Playwright Rust Target API Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/technical/v0.1-slice1-initialization-flow-research.md This is the target API example for the Playwright Rust library. It shows how to launch Playwright, access browser types, and print their names. Ensure Tokio is set up for async operations. ```rust use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), Box> { let playwright = Playwright::launch().await?; println!("Chromium: {}", playwright.chromium().name()); println!("Firefox: {}", playwright.firefox().name()); println!("WebKit: {}", playwright.webkit().name()); Ok(()) } ``` -------------------------------- ### Direct CDP Implementation Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/adr/0001-protocol-architecture.md Illustrates a direct implementation of the Chrome DevTools Protocol (CDP) for browser communication. This approach requires manual handling of WebSocket connections and command mapping. ```rust pub struct ChromiumBrowser { websocket: WebSocket, } impl ChromiumBrowser { pub async fn navigate(&self, url: &str) -> Result<()> { let command = json!({ "id": self.next_id(), "method": "Page.navigate", "params": { "url": url } }); self.websocket.send(command).await?; // Wait for response, handle events... Ok(()) } } ``` -------------------------------- ### Playwright Rust Example Output Source: https://github.com/padamson/playwright-rust/blob/main/docs/technical/v0.1-technical-summary.md Expected output when running the basic Playwright Rust example, showing the Playwright server launch and available browser types with their paths. ```text 🚀 Launching Playwright... ✅ Playwright launched successfully! 📦 Available browser types: • Chromium: target/debug/build/playwright-rs-/out/playwright-driver/playwright--/node_modules/playwright-core/... • Firefox: target/debug/build/playwright-rs-/out/playwright-driver/playwright--/node_modules/playwright-core/... • WebKit: target/debug/build/playwright-rs-/out/playwright-driver/playwright--/node_modules/playwright-core/... ``` -------------------------------- ### Java Root Initialization Source: https://github.com/padamson/playwright-rust/blob/main/docs/adr/0002-initialization-flow.md Shows the Java implementation for initializing the root object, sending the 'initialize' message, and retrieving the Playwright object using its GUID from the response. ```java class Root extends ChannelOwner { PlaywrightImpl initialize() { JsonObject params = new JsonObject(); params.addProperty("sdkLanguage", "java"); JsonElement result = sendMessage("initialize", params, NO_TIMEOUT); String guid = result.getAsJsonObject() .getAsJsonObject("playwright") .get("guid") .getAsString(); return connection.getExistingObject(guid); } } ``` -------------------------------- ### Playwright::launch Source: https://context7.com/padamson/playwright-rust/llms.txt Initializes the Playwright server and returns the root handle for accessing browser types. This is the typical starting point for any playwright-rust application. ```APIDOC ## Playwright::launch ### Description Initializes the Playwright server and returns the root `Playwright` handle. This handle is used to access different browser types and the headless HTTP API. ### Usage ```rust use playwright_rs::Playwright; #[tokio::main] async fn main() -> Result<(), Box> { // Launch the Playwright server let pw = Playwright::launch().await?; // Access browser types let chromium = pw.chromium(); let firefox = pw.firefox(); let webkit = pw.webkit(); // Access headless HTTP API let request_api = pw.request(); // Graceful shutdown pw.shutdown().await?; Ok(()) } ``` ### Notes - One `Playwright` instance per process is typical. - The `PLAYWRIGHT_VERSION` constant provides the bundled Playwright driver version. ``` -------------------------------- ### Run All Tests with Nextest Source: https://github.com/padamson/playwright-rust/blob/main/CLAUDE.md Execute all tests in the project using the `cargo-nextest` tool. Ensure `cargo-nextest` is installed. ```bash cargo nextest run ``` -------------------------------- ### User code example for evaluate() with typed arguments and returns Source: https://github.com/padamson/playwright-rust/blob/main/docs/adr/0004-generic-evaluate.md Demonstrates how user code can define a struct, pass it as an argument to `evaluate()`, and receive a typed result. ```rust #[derive(Serialize, Deserialize)] struct Point { x: i32, y: i32 } let point = Point { x: 10, y: 20 }; let result: Point = page.evaluate( "(arg) => ({x: arg.x * 2, y: arg.y * 2})", Some(&point) ).await?; ``` -------------------------------- ### Modifier Key Parsing Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.5-advanced-testing.md Shows how to use modifier keys with the `Keyboard.press()` method, allowing for compound key presses like 'Control+A'. ```rust Keyboard.press with compound keys (e.g., "Control+A") ``` -------------------------------- ### Synchronous API Ingest Photo Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/templates/TEMPLATE_ADR.md Illustrates the usage of a synchronous API for ingesting a photo. This approach is suitable for simpler I/O operations where blocking is acceptable. ```rust pub fn ingest_photo(source: &Path, dest: &Path) -> Result { // Implementation approach } ``` -------------------------------- ### Asynchronous API Ingest Photo Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/templates/TEMPLATE_ADR.md Demonstrates the usage of an asynchronous API for ingesting a photo. This is beneficial for I/O-bound operations, especially network requests, to avoid blocking the main thread. ```rust pub async fn ingest_photo(source: &Path, dest: &Path) -> Result { // Implementation approach } ``` -------------------------------- ### Example: Passing Arguments and Typed Returns Source: https://github.com/padamson/playwright-rust/blob/main/docs/adr/0004-generic-evaluate.md Demonstrates how to use the `evaluate` method to pass a Rust struct as an argument to a JavaScript function and receive a typed result. ```APIDOC ## Example: Passing Arguments and Typed Returns ### Description This example shows how to call `page.evaluate` with a JavaScript function that expects an argument, passing a Rust struct and expecting a typed result. ### Code ```rust use serde::{Serialize, Deserialize}; #[derive(Serialize)] struct Point { x: i32, y: i32, } #[derive(Deserialize)] struct SumResult { sum: i32, } async fn example(page: &playwright_rust::Page) -> Result { let point_arg = Point { x: 10, y: 20 }; let result: SumResult = page.evaluate( "(arg) => ({ sum: arg.x + arg.y })", Some(&point_arg) ).await?; Ok(result) } ``` ``` -------------------------------- ### Trait-based Route Handler Usage Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/technical/v0.5-slice4-routing-architecture.md Illustrates how to use the trait-based route handler with an async closure to abort network requests for specific file types. ```rust page.route("**/*.png", |route| async move { route.abort(None).await }).await?; ``` -------------------------------- ### Using tokio::sync::Mutex Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.1-protocol-foundation.md Example demonstrating the necessity of `tokio::sync::Mutex` for locks held across await points in asynchronous operations, contrasting with `std::sync::Mutex`. ```rust use tokio::sync::Mutex; // ... inside an async function ... let mut guard = mutex.lock().await; // Perform operations with guard // guard is dropped here, releasing the lock ``` -------------------------------- ### Get Playwright Driver Executable Path Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.1-protocol-foundation.md Locates the Playwright driver executable and its associated CLI script. It checks in order: the bundled driver in `drivers/`, the `PLAYWRIGHT_DRIVER_PATH` environment variable, and npm installations. ```rust pub fn get_driver_executable() -> Result<(PathBuf, PathBuf)> { // ... implementation details ... } ``` -------------------------------- ### Python RootChannelOwner Initialization Source: https://github.com/padamson/playwright-rust/blob/main/docs/adr/0002-initialization-flow.md Demonstrates the Python implementation of initializing the root channel owner and sending the 'initialize' message with the SDK language. ```python class RootChannelOwner(ChannelOwner): def __init__(self, connection: "Connection") -> None: super().__init__(connection, "Root", "", {}) async def initialize(self) -> "Playwright": return from_channel( await self._channel.send( "initialize", {"sdkLanguage": "python"}, ) ) ``` -------------------------------- ### Control Time with Fake Clock for Tests Source: https://context7.com/padamson/playwright-rust/llms.txt Use `page.clock()` or `context.clock()` to replace the page's `Date`, `setTimeout`, and `setInterval` with a controllable fake clock. Call `install` before navigating so page scripts see the fake clock from the start. ```rust use playwright_rs::Playwright; use playwright_rs::protocol::ClockInstallOptions; #[tokio::main] async fn main() -> Result<(), Box> { let pw = Playwright::launch().await?; let browser = pw.chromium().launch().await?; let page = browser.new_page().await?; // Install fake timers before page load let clock = page.clock().expect("clock not available"); clock.install(Some(ClockInstallOptions { time: Some(0) })).await?; page.set_content(r"
", None).await?; // Freeze time at a specific epoch (2023-11-14T22:13:20Z) clock.pause_at(1_700_000_000_000).await?; let now: String = page.evaluate_value("new Date().toISOString()").await?; println!("paused at: {}", now); // 2023-11-14T22:13:20.000Z // Advance 60 seconds — all due timers fire clock.fast_forward(60_000).await?; let after: String = page.evaluate_value("new Date().toISOString()").await?; println!("after fast_forward: {}", after); // +60s // Freeze Date.now() while letting timers keep ticking clock.set_fixed_time(0).await?; let frozen: String = page.evaluate_value("Date.now().toString()").await?; println!("frozen: {}", frozen); // "0" // Resume real time clock.resume().await?; // Set system time without freezing clock.set_system_time(1_700_000_000_000).await?; browser.close().await?; Ok(()) } ``` -------------------------------- ### Launch Playwright Server and Initialize Source: https://github.com/padamson/playwright-rust/blob/main/docs/adr/0002-initialization-flow.md Launches the Playwright server, establishes a connection, and initializes the Playwright instance. This is the primary entry point for using the high-level API. ```rust pub struct Playwright { inner: Arc, connection: Arc, } impl Playwright { pub async fn launch() -> Result { // 1. Launch server let mut server = PlaywrightServer::launch().await?; // 2. Create transport let stdin = server.process.stdin.take().unwrap(); let stdout = server.process.stdout.take().unwrap(); let (transport, message_rx) = PipeTransport::new(stdin, stdout); // 3. Create connection let connection = Arc::new(Connection::new(transport, message_rx)); // 4. Spawn message loop let conn = Arc::clone(&connection); tokio::spawn(async move { conn.run().await }); // 5. Initialize (synchronous, blocks until complete) let inner = connection.initialize_playwright().await?; Ok(Self { inner, connection }) } pub fn chromium(&self) -> &BrowserType { self.inner.chromium() } pub fn firefox(&self) -> &BrowserType { self.inner.firefox() } pub fn webkit(&self) -> &BrowserType { self.inner.webkit() } } ``` -------------------------------- ### Launch Browser with Options Source: https://context7.com/padamson/playwright-rust/llms.txt Launches a browser instance with custom options, including headless mode, slow-motion, timeouts, custom arguments, and download paths. The `LaunchOptions` builder pattern is used for configuration. ```rust use playwright_rs::{LaunchOptions, Playwright}; use playwright_rs::api::IgnoreDefaultArgs; #[tokio::main] async fn main() -> Result<(), Box> { let pw = Playwright::launch().await?; // Headed launch with options let opts = LaunchOptions::new() .headless(false) .slow_mo(50.0) .timeout(60_000.0) .args(vec!["--no-sandbox".to_string(), "--disable-gpu".to_string()]) .downloads_path("/tmp/downloads".to_string()); let browser2 = pw.chromium().launch_with_options(opts).await?; // browser_type back-reference println!("engine: {}", browser2.browser_type().name()); // contexts() lists open contexts println!("open contexts: {}", browser2.contexts().len()); // ... other code ... browser2.close().await?; Ok(()) } ``` -------------------------------- ### Launch Browser and Navigate (Python) Source: https://github.com/padamson/playwright-rust/blob/main/README.md Demonstrates launching a Chromium browser, creating a new page, navigating to a URL, and asserting text content using Playwright for Python. ```python from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch() page = browser.new_page() page.goto("https://example.com") # Locator with auto-waiting heading = page.locator("h1") assert heading.text_content() == "Example Domain" # Response body access resp = page.goto("https://api.example.com/data") data = resp.json() browser.close() ``` -------------------------------- ### Rust Code Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/templates/TEMPLATE_ADR.md This is a placeholder for a Rust code example. It is intended to demonstrate a specific implementation or concept related to Playwright in Rust. ```rust // Example ``` -------------------------------- ### Launch Browser and Navigate (Rust) Source: https://github.com/padamson/playwright-rust/blob/main/README.md Demonstrates launching a Chromium browser, creating a new page, navigating to a URL, and asserting text content using Playwright for Rust. Requires `serde_json` for JSON parsing. ```rust use playwright_rs::Playwright; let pw = Playwright::launch().await?; let browser = pw.chromium().launch().await?; let page = browser.new_page().await?; page.goto("https://example.com", None).await?; // Locator with auto-waiting let heading = page.locator("h1").await; assert_eq!(heading.text_content().await?, Some("Example Domain".into())); // Response body access let resp = page.goto("https://api.example.com/data", None).await?.unwrap(); let data: serde_json::Value = resp.json().await?; browser.close().await?; ``` -------------------------------- ### Create Isolated Browser Contexts and Pages Source: https://context7.com/padamson/playwright-rust/llms.txt Demonstrates creating a new browser context with custom options like viewport, locale, timezone, geolocation, and video recording. A new page is then created within this context. ```rust use playwright_rs::{ BrowserContextOptions, Cookie, Geolocation, Playwright, RecordVideo, Viewport, }; #[tokio::main] async fn main() -> Result<(), Box> { let pw = Playwright::launch().await?; let browser = pw.chromium().launch().await?; // Fully-configured isolated context let ctx = browser.new_context_with_options( BrowserContextOptions::builder() .viewport(Viewport { width: 1280, height: 720 }) .locale("en-US".to_string()) .timezone_id("America/New_York".to_string()) .geolocation(Geolocation { latitude: 40.71, longitude: -74.0, accuracy: None }) .record_video(RecordVideo { dir: "/tmp/videos".to_string(), size: None }) .build() ).await?; let page = ctx.new_page().await?; page.goto("https://example.com", None).await?; println!("title: {}", page.title().await?); println!("url: {}", page.url()); // Wait for a new page popup let waiter = ctx.expect_page(Some(5_000.0)).await?; // ... trigger popup ... // let popup = waiter.wait().await?; ctx.close().await?; browser.close().await?; Ok(()) } ``` -------------------------------- ### Registering Routes with Pattern Matching Source: https://github.com/padamson/playwright-rust/blob/main/docs/technical/v0.5-slice4-routing-architecture.md Demonstrates how to register routes with different patterns. The more specific pattern ('**/*.png') takes precedence over the general one ('**/*') due to the 'last registered wins' strategy. ```rust page.route("**/*", continue_handler).await?; page.route("**/*.png", abort_handler).await?; ``` -------------------------------- ### JavaScript Playwright Route Abort Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/technical/v0.5-slice4-routing-architecture.md Presents the JavaScript Playwright API for aborting a route. This example is compared against the Rust implementation, particularly concerning concurrency handling. ```javascript await page.route("**/*.png", route => route.abort()); ``` -------------------------------- ### Install Gnuplot for Visualization Source: https://github.com/padamson/playwright-rust/blob/main/docs/benchmarking.md Install Gnuplot on macOS or Linux to enable criterion.rs to generate additional SVG plots alongside the HTML reports. This provides more detailed visualization options. ```bash # macOS brew install gnuplot # Linux sudo apt-get install gnuplot ``` -------------------------------- ### Launch Browser Instance Source: https://context7.com/padamson/playwright-rust/llms.txt Launches a managed browser instance using the default headless configuration. The `browser.name()` and `browser.version()` methods can be used to inspect the launched browser. ```rust use playwright_rs::Playwright; #[tokio::main] async fn main() -> Result<(), Box> { let pw = Playwright::launch().await?; // Default headless launch let browser = pw.chromium().launch().await?; println!("{} {}", browser.name(), browser.version()); // chromium 131.0... // ... other code ... browser.close().await?; Ok(()) } ``` -------------------------------- ### Entry Point: High-Level API for Launching Playwright Source: https://github.com/padamson/playwright-rust/blob/main/docs/adr/0001-protocol-architecture.md The Playwright::launch() function provides a high-level API to orchestrate the full initialization of the Playwright instance. ```rust Playwright::launch() ``` -------------------------------- ### Java Playwright Route Abort Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/technical/v0.5-slice4-routing-architecture.md Shows the Java Playwright API for aborting a route, similar to the Python example. It highlights the callback-based pattern used across different language bindings. ```java page.route("**/*.png", route -> route.abort()); ``` -------------------------------- ### Initialize Playwright Server Source: https://context7.com/padamson/playwright-rust/llms.txt Launches the bundled Node.js Playwright server and obtains the root handle. This is the entry point for interacting with Playwright functionalities. ```rust use playwright_rs::Playwright; #[tokio::main] async fn main() -> Result<(), Box> { let pw = Playwright::launch().await?; // Access the three browser engines let chromium = pw.chromium(); let firefox = pw.firefox(); let webkit = pw.webkit(); println!("Playwright driver version: {}", playwright_rs::PLAYWRIGHT_VERSION); // Access headless HTTP API (no browser needed) let request_api = pw.request(); // Graceful shutdown pw.shutdown().await?; Ok(()) } ``` -------------------------------- ### BrowserType::launch / BrowserType::launch_with_options Source: https://context7.com/padamson/playwright-rust/llms.txt Launches a managed browser instance. Supports various options for configuration, such as headless mode, slow motion, timeouts, and custom arguments. ```APIDOC ## BrowserType::launch / BrowserType::launch_with_options ### Description Launches a managed browser instance. `launch()` uses default options, while `launch_with_options()` allows detailed configuration via `LaunchOptions`. ### Usage ```rust use playwright_rs::{LaunchOptions, Playwright}; use playwright_rs::api::IgnoreDefaultArgs; #[tokio::main] async fn main() -> Result<(), Box> { let pw = Playwright::launch().await?; // Launch with default options (headless) let browser = pw.chromium().launch().await?; println!("Launched browser: {} {}", browser.name(), browser.version()); // Launch with custom options let opts = LaunchOptions::new() .headless(false) .slow_mo(50.0) .timeout(60_000.0) .args(vec!["--no-sandbox".to_string(), "--disable-gpu".to_string()]) .downloads_path("/tmp/downloads".to_string()); let browser2 = pw.chromium().launch_with_options(opts).await?; println!("Launched browser with options. Open contexts: {}", browser2.contexts().len()); // Close browsers browser.close().await?; browser2.close().await?; Ok(()) } ``` ### Options (`LaunchOptions`) - `headless`: `bool` - Whether to run the browser in headless mode. - `slow_mo`: `f64` - Slow down operations by the specified milliseconds. - `timeout`: `f64` - Maximum time in milliseconds to wait for operations. - `args`: `Vec` - Arguments to pass to the browser instance. - `downloads_path`: `String` - Path for browser downloads. ``` -------------------------------- ### .NET Message Framing Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.1-protocol-foundation.md Shows how .NET encodes message length using byte masks. ```csharp Byte masks `(len >> 8) & 0xFF` for encoding ``` -------------------------------- ### Display CLI Help Text Source: https://github.com/padamson/playwright-rust/blob/main/docs/templates/TEMPLATE_IMPLEMENTATION_PLAN.md Show the help text for a given media command. This ensures that the CLI help text is accurate and helpful as part of the definition of done. ```bash media [command] --help ``` -------------------------------- ### Get Attribute Value in Playwright Rust Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.3-page-interactions.md Use `locator.get_attribute(name)` to retrieve the value of a specified attribute from an element. ```rust let img_locator = page.locator("img#logo"); let src_attribute = img_locator.get_attribute("src").await?; println!("Image source: {:?}", src_attribute); ``` -------------------------------- ### Count Matching Elements in Playwright Rust Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.3-page-interactions.md Use `locator.count()` to get the number of elements that match the locator's selector. ```rust let list_items = page.locator("ul.items li"); let count = list_items.count().await?; println!("Number of list items: {}", count); ``` -------------------------------- ### Compare Performance After Optimization Source: https://github.com/padamson/playwright-rust/blob/main/docs/benchmarking.md After implementing optimizations, run this command to compare the new performance against the 'before' baseline. Criterion will display the percentage change for each benchmark. ```bash # See the performance impact cargo bench -- --baseline before-guid-optimization ``` -------------------------------- ### Playwright Object Initializer Structure Source: https://github.com/padamson/playwright-rust/blob/main/docs/technical/v0.1-slice1-initialization-flow-research.md Illustrates the structure of the initializer for the Playwright object, showing how it references BrowserType objects by their GUIDs. ```json { "chromium": { "guid": "browserType@chromium" }, "firefox": { "guid": "browserType@firefox" }, "webkit": { "guid": "browserType@webkit" } } ``` -------------------------------- ### Playwright-Rust Repository Structure Source: https://github.com/padamson/playwright-rust/blob/main/CLAUDE.md Overview of the directory layout for the playwright-rust project, indicating the location of core crates, tests, examples, and documentation. ```plaintext crates/playwright/ single crate (consolidated from playwright-core in v0.7) src/api/ launch options, connect options src/protocol/ protocol objects (Page, Browser, Locator, ...) src/server/ connection, transport, channel, object factory src/assertions.rs expect API (auto-retry assertions) src/error.rs error types tests/integration/ integration tests examples/ usage examples fuzz/ cargo-fuzz targets drivers/ Playwright server binaries (gitignored) supply-chain/ cargo-vet audit config (see skill) docs/ roadmap, ADRs, implementation plans, technical notes .claude/agents/ specialized sub-agents (see below) .claude/skills/ procedural reference (see below) ``` -------------------------------- ### JSON-RPC Request Structure Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.1-protocol-foundation.md Defines the structure for outgoing JSON-RPC requests, including a unique ID, target GUID, method, and parameters. ```rust struct Request { id: u32, guid: String, method: String, params: JsonValue, } ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/padamson/playwright-rust/blob/main/docs/benchmarking.md Execute all defined benchmarks and compare results against the previous run. Ensure you have criterion.rs integrated for this functionality. ```bash cargo bench ``` -------------------------------- ### Java Message Framing Example Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.1-protocol-foundation.md Demonstrates Java's approach to message framing using bit shifting to encode each byte of the length. ```java Bit shifting `(v >>> 8) & 0xFF` for each byte ``` -------------------------------- ### Playwright::launch() Source: https://github.com/padamson/playwright-rust/blob/main/docs/implementation-plans/v0.1-protocol-foundation.md Launches a Playwright instance, establishing a connection to the Playwright server and providing access to browser types. ```APIDOC ## Playwright::launch() ### Description Launches a Playwright instance. This is the primary entry point for interacting with Playwright in Rust. It handles the server launch, connection setup, and initialization of browser types. ### Method `async fn launch() -> Result` ### Parameters None ### Returns - `Result`: A `Result` containing the `Playwright` instance on success, or an error if the launch fails. ### Request Example ```rust use playwright::Playwright; #[tokio::main] async fn main() -> Result<(), Box> { let playwright = Playwright::launch().await?; println!("Playwright launched successfully!"); Ok(()) } ``` ### Response #### Success Response (200) - `Playwright`: An instance of the `Playwright` struct, which provides access to browser types. #### Response Example (Conceptual - actual Playwright instance is returned) ```json { "status": "success", "data": "Playwright instance" } ``` ```