### Install Browser Cash SDK Source: https://docs.browser.cash/docs/introduction/getting-started Install the Browser Cash SDK using npm, yarn, or pnpm. The SDK is available for TypeScript/JavaScript. ```bash npm install @browsercash/sdk ``` ```bash yarn add @browsercash/sdk ``` ```bash pnpm add @browsercash/sdk ``` -------------------------------- ### Quick Start: Manage Browser Sessions with SessionPool Source: https://docs.browser.cash/docs/fundamentals/concurrent-browser-sessions Demonstrates how to initialize a SessionPool, acquire a session, perform browser operations using Playwright, and release the session back to the pool. It includes basic setup and usage patterns. ```typescript import { chromium } from "playwright-core"; import { SessionPool } from "@browsercash/pool"; const pool = new SessionPool({ apiKey: process.env.BROWSER_API_KEY!, chromium: chromium, size: 3, // Maintain 3 concurrent sessions }); await pool.init(); // Acquire a session from the pool const session = await pool.acquire(); // Use standard Playwright operations const page = await session.browser.newPage(); await page.goto("https://example.com"); console.log(await page.title()); await page.close(); // Return session to the pool pool.release(session); // Cleanup when done await pool.shutdown(); ``` -------------------------------- ### Browser Session API Source: https://docs.browser.cash/docs/introduction/getting-started This section details the API endpoints for managing browser sessions, including creating and stopping sessions. ```APIDOC ## POST /v1/browser/session ### Description Creates a new browser session. This session provides a CDP URL that can be used with browser automation tools like Playwright, Puppeteer, or Selenium. ### Method POST ### Endpoint /v1/browser/session ### Parameters #### Query Parameters None #### Request Body - **None** ### Request Example ```json {} ``` ### Response #### Success Response (200) - **cdpUrl** (string) - The CDP URL for the created session. - **sessionId** (string) - The unique identifier for the session. #### Response Example ```json { "cdpUrl": "wss://cdp.browser.cash/session/SESSION_ID", "sessionId": "SESSION_ID" } ``` --- ## DELETE /v1/browser/session ### Description Stops an existing browser session, releasing its resources. ### Method DELETE ### Endpoint /v1/browser/session ### Parameters #### Query Parameters - **sessionId** (string) - Required - The ID of the session to stop. #### Request Body - **None** ### Request Example ```bash curl -X DELETE "https://api.browser.cash/v1/browser/session?sessionId=SESSION_ID" \ -H "Authorization: Bearer $BROWSER_API_KEY" ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the session was stopped. #### Response Example ```json { "message": "Session SESSION_ID stopped successfully." } ``` ``` -------------------------------- ### Create and Manage Browser Session with SDK (TypeScript) Source: https://docs.browser.cash/docs/introduction/getting-started Create a new browser session using the BrowsercashSDK, log the CDP URL, and stop the session when finished. Requires an API key. ```typescript import BrowsercashSDK from "@browsercash/sdk"; const client = new BrowsercashSDK({ apiKey: process.env.BROWSER_API_KEY, }); // Create a session const session = await client.browser.session.create(); console.log("CDP URL:", session.cdpUrl); // Use the CDP URL with Playwright, Puppeteer, etc. // ... // Stop the session when done await client.browser.session.stop({ sessionId: session.sessionId }); ``` -------------------------------- ### Create and Manage Browser Session with cURL Source: https://docs.browser.cash/docs/introduction/getting-started Create a browser session using cURL by sending a POST request, and stop the session with a DELETE request. Requires an API key. ```bash # Create a session curl -X POST https://api.browser.cash/v1/browser/session \ -H "Authorization: Bearer $BROWSER_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' # Response includes cdpUrl - connect with any CDP client # Stop the session when done curl -X DELETE "https://api.browser.cash/v1/browser/session?sessionId=SESSION_ID" \ -H "Authorization: Bearer $BROWSER_API_KEY" ``` -------------------------------- ### Install Browser-Use and Dependencies Source: https://docs.browser.cash/docs/integrations/browser-use Installs the browser-use package and requests library using uv, a Python package installer. This command initializes a new Python environment and synchronizes dependencies, requiring Python 3.11 or higher. ```bash # Create environment with uv (Python >= 3.11) uv init uv add browser-use requests uv sync ``` -------------------------------- ### Install Crawl4AI and Dependencies Source: https://docs.browser.cash/docs/integrations/crawl4ai Installs the Crawl4AI package and the requests library using uv, a Python package installer. This command creates a virtual environment and synchronizes dependencies. ```bash uv init uv add crawl4ai requests uv sync ``` -------------------------------- ### Create and Manage Browser Session with REST API (Python) Source: https://docs.browser.cash/docs/introduction/getting-started Create a browser session using the REST API by sending a POST request, then delete the session using its ID. Requires an API key. ```python import os import requests # Create a session resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", }, json={} ) session = resp.json() print("CDP URL:", session["cdpUrl"]) # Use the CDP URL with Playwright, Selenium, etc. # ... # Stop the session when done requests.delete( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}"}, params={"sessionId": session["sessionId"]} ) ``` -------------------------------- ### Stagehand Quick Start with Browser Cash SDK (TypeScript) Source: https://docs.browser.cash/docs/integrations/stagehand A comprehensive example demonstrating how to initialize Stagehand with a Browser Cash session, perform actions on a webpage using natural language, extract structured data, and clean up resources. It requires a BROWSER_API_KEY environment variable. ```typescript import { Stagehand } from '@browserbasehq/stagehand'; import BrowsercashSDK from '@browsercash/sdk'; async function run() { const client = new BrowsercashSDK({ apiKey: process.env.BROWSER_API_KEY!, }); // Create Browser Cash session const session = await client.browser.session.create(); // Initialize Stagehand with Browser Cash CDP URL const stagehand = new Stagehand({ env: 'LOCAL', localBrowserLaunchOptions: { cdpUrl: session.cdpUrl, }, }); await stagehand.init(); // Use natural language to interact with pages await stagehand.page.goto('https://example.com'); await stagehand.act({ action: 'click on the login button' }); await stagehand.act({ action: 'type "user@example.com" in the email field' }); await stagehand.act({ action: 'type "password123" in the password field' }); await stagehand.act({ action: 'click submit' }); // Extract data using natural language const data = await stagehand.extract({ instruction: 'Extract the user profile information', schema: { type: 'object', properties: { name: { type: 'string' }, email: { type: 'string' }, }, }, }); console.log(data); // Cleanup await stagehand.close(); await client.browser.session.stop({ sessionId: session.sessionId }); } run().catch(console.error); ``` -------------------------------- ### Install Browser Cash Pool and Playwright Core Source: https://docs.browser.cash/docs/fundamentals/concurrent-browser-sessions Installs the necessary packages for managing browser sessions. The `@browsercash/pool` package depends on `playwright-core`. ```bash npm install @browsercash/pool playwright-core ``` -------------------------------- ### Install Selenium and Requests Source: https://docs.browser.cash/docs/integrations/selenium Installs the necessary Python packages for Selenium and making HTTP requests, and the JavaScript Selenium WebDriver package. ```bash pip install selenium requests ``` ```bash npm install selenium-webdriver ``` -------------------------------- ### Install Puppeteer Core and Browser Cash SDK Source: https://docs.browser.cash/docs/integrations/puppeteer Installs the necessary packages for Puppeteer Core and the Browser Cash SDK. It's recommended to use `puppeteer-core` as Browser Cash provides the browser instance. ```bash npm install puppeteer-core @browsercash/sdk ``` -------------------------------- ### Define Complex Agent Tasks (Python) Source: https://docs.browser.cash/docs/integrations/browser-use Illustrates how to define a multi-step task for an AI agent. This example instructs the agent to navigate to Amazon.com, search for a product, identify a top-rated item within a price range, and extract specific details. ```python agent = Agent( task=""" 1. Go to Amazon.com 2. Search for "wireless headphones" 3. Find the top-rated product under $100 4. Extract the product name, price, and rating """, llm=llm, browser=browser, ) ``` -------------------------------- ### Install Stagehand and Browsercash SDK Source: https://docs.browser.cash/docs/integrations/stagehand Installs the necessary packages for Stagehand and the Browsercash SDK using npm. These packages enable AI-native browser automations and interaction with the Browser Cash platform. ```bash npm install @browserbasehq/stagehand @browsercash/sdk ``` -------------------------------- ### SOCKS5 Proxy URL Format Examples Source: https://docs.browser.cash/docs/features/proxies Provides examples of valid SOCKS5 proxy URL formats for use with Browser Cash. This includes configurations with and without authentication, and using IP addresses. ```typescript // Without authentication proxyUrl: "socks5://proxy.example.com:1080"; // With authentication proxyUrl: "socks5://myuser:mypass@proxy.example.com:1080"; // With IP address proxyUrl: "socks5://user:pass@192.168.1.100:1080"; ``` ```python # Without authentication proxy_url = "socks5://proxy.example.com:1080" # With authentication proxy_url = "socks5://myuser:mypass@proxy.example.com:1080" # With IP address proxy_url = "socks5://user:pass@192.168.1.100:1080" ``` -------------------------------- ### Dynamic Resizing Source: https://docs.browser.cash/docs/features/window-size Dynamically resize the browser viewport after a session has been established using provided code examples. ```APIDOC ## Dynamic Resizing ### Description After connecting to a browser session, you can dynamically resize the viewport using the following methods. ### Method N/A (Client-side operation) ### Endpoint N/A ### Parameters #### Request Body (Conceptual) - **width** (number) - Required - The desired width of the viewport. - **height** (number) - Required - The desired height of the viewport. ### Request Example ```typescript // Playwright (TypeScript) await page.setViewportSize({ width: 1920, height: 1080 }); ``` ```typescript // Puppeteer (TypeScript) await page.setViewport({ width: 1920, height: 1080 }); ``` ```python # Playwright (Python) page.set_viewport_size({"width": 1920, "height": 1080}) ``` ### Response N/A (Client-side operation, no direct API response for this action) ``` -------------------------------- ### Python Quick Start: Connect Browser Cash to Selenium Source: https://docs.browser.cash/docs/integrations/selenium Demonstrates how to create a Browser Cash session, connect Selenium to it using the CDP URL, perform basic automation like navigating to a URL and printing the title, and then clean up the session. ```python from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By import requests import os # Create Browser Cash session resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", }, json={} ) resp.raise_for_status() data = resp.json() cdp_url = data["cdpUrl"] session_id = data["sessionId"] # Connect Selenium via CDP options = Options() options.add_experimental_option( "debuggerAddress", cdp_url.replace("wss://", "").replace("ws://", "").split("/")[0] ) driver = webdriver.Chrome(options=options) # Automate driver.get("https://example.com") print(driver.title) # Cleanup driver.quit() requests.delete( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}"}, params={"sessionId": session_id} ) ``` -------------------------------- ### Quick Start Crawl4AI with Browser Cash Source: https://docs.browser.cash/docs/integrations/crawl4ai Demonstrates how to use Crawl4AI with Browser Cash's stealth browsers. It creates a browser session, configures the crawler, runs a crawl on a specified URL, and prints the Markdown output. Finally, it cleans up the browser session. ```python import os import asyncio import requests from crawl4ai import AsyncWebCrawler, BrowserConfig async def main(): # Create Browser Cash session resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {os.getenv('BROWSER_CASH_API_KEY')}", "Content-Type": "application/json", }, json={}, ) resp.raise_for_status() data = resp.json() # Configure Crawl4AI to use the Browser Cash browser browser_config = BrowserConfig( cdp_url=data["cdpUrl"], use_managed_browser=True, ) # Run the crawler async with AsyncWebCrawler(config=browser_config) as crawler: result = await crawler.arun( url="https://www.nbcnews.com/business", ) print(result.markdown) # Cleanup requests.delete( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {os.getenv('BROWSER_CASH_API_KEY')}"}, params={"sessionId": data["sessionId"]}, ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Playwright and Browser Cash SDK Source: https://docs.browser.cash/docs/integrations/playwright Installs the necessary packages for Playwright and the Browser Cash SDK using npm for Node.js or pip for Python. For Python, it also downloads the Chromium browser. ```bash npm install playwright @browsercash/sdk ``` ```bash pip install playwright requests playwright install chromium ``` -------------------------------- ### Stagehand Complex Workflow Example (TypeScript) Source: https://docs.browser.cash/docs/integrations/stagehand An example of building a multi-step checkout workflow using Stagehand. It includes searching for a product, adding it to the cart, proceeding to checkout, and extracting summary information, showcasing error handling and sequential actions. ```typescript // Multi-step workflow with error handling async function checkoutFlow(stagehand: Stagehand) { await stagehand.page.goto('https://shop.example.com'); await stagehand.act({ action: 'search for "laptop"' }); await stagehand.act({ action: 'click on the first product' }); await stagehand.act({ action: 'add to cart' }); await stagehand.act({ action: 'go to checkout' }); const cartSummary = await stagehand.extract({ instruction: 'Extract the cart total and item count', schema: { type: 'object', properties: { total: { type: 'string' }, itemCount: { type: 'number' }, }, }, }); return cartSummary; } ``` -------------------------------- ### Python: Taking Screenshots with Selenium Source: https://docs.browser.cash/docs/integrations/selenium Provides examples for capturing full-page screenshots and screenshots of specific elements using the Selenium WebDriver. Assumes a driver instance is available. ```python driver.save_screenshot("screenshot.png") # Screenshot specific element element = driver.find_element(By.ID, "content") element.screenshot("element.png") ``` -------------------------------- ### Combine Country and Node Selection for Browser Sessions Source: https://docs.browser.cash/docs/features/geolocation Illustrates how to first create a session targeting a specific country and then use the returned node ID to create subsequent sessions targeting the exact same node. This ensures consistent location and node usage across sessions. Examples are provided for TypeScript, Python, and cURL. ```typescript // First session — let Browser Cash pick a US node const session1 = await client.browser.session.create({ country: "US", }); // Save the node ID for later const nodeId = session1.servedBy; // Later — target the exact same node const session2 = await client.browser.session.create({ nodeId: nodeId, }); ``` ```python import os import requests headers = { "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", } # First session — let Browser Cash pick a US node resp1 = requests.post( "https://api.browser.cash/v1/browser/session", headers=headers, json={"country": "US"} ) session1 = resp1.json() # Save the node ID for later node_id = session1["servedBy"] # Later — target the exact same node resp2 = requests.post( "https://api.browser.cash/v1/browser/session", headers=headers, json={"nodeId": node_id} ) session2 = resp2.json() ``` ```bash # First session — let Browser Cash pick a US node curl -X POST https://api.browser.cash/v1/browser/session \ -H "Authorization: Bearer $BROWSER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"country": "US"}' # Response includes servedBy field with the node ID # Use it to target the same node later curl -X POST https://api.browser.cash/v1/browser/session \ -H "Authorization: Bearer $BROWSER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"nodeId": "node-us-east-abc123"}' ``` -------------------------------- ### Configure High-Throughput Browser Session Pool Source: https://docs.browser.cash/docs/fundamentals/concurrent-browser-sessions Example configuration for a SessionPool optimized for high throughput, featuring a larger number of concurrent browsers, frequent session recycling, and a waiting queue for busy pools. ```typescript const pool = new SessionPool({ apiKey: process.env.BROWSER_API_KEY!, chromium: chromium, size: 10, // 10 concurrent browsers maxUses: 100, // Recycle after 100 uses maxAgeMs: 600000, // 10 minute max lifetime enableWaitQueue: true, // Queue when pool is full }); ``` -------------------------------- ### Configure Long-Running Browser Session Pool with Health Checks Source: https://docs.browser.cash/docs/fundamentals/concurrent-browser-sessions Example configuration for a SessionPool designed for long-running tasks, including enabled health checks to monitor session status and a longer maximum session lifetime. ```typescript const pool = new SessionPool({ apiKey: process.env.BROWSER_API_KEY!, chromium: chromium, size: 5, enableHealthCheck: true, // Monitor session health healthCheckIntervalMs: 15000, // Check every 15 seconds maxAgeMs: 1800000, // 30 minute max lifetime }); ``` -------------------------------- ### Dynamically Resize Browser Viewport Source: https://docs.browser.cash/docs/features/window-size Adjust the browser viewport dimensions after a session has been established. This is useful for responsive testing and adapting to different website layouts. Examples are provided for Playwright and Puppeteer using TypeScript and Python. ```typescript await page.setViewportSize({ width: 1920, height: 1080 }); ``` ```typescript await page.setViewport({ width: 1920, height: 1080 }); ``` ```python page.set_viewport_size({"width": 1920, "height": 1080}) ``` -------------------------------- ### Run an AI Agent with Browser Cash Integration (Python) Source: https://docs.browser.cash/docs/integrations/browser-use Demonstrates how to create and run an AI agent using Browser-Use and Browser Cash. It initializes a Browser Cash session, configures a Browser-Use browser with the CDP URL, and then executes an agent task. Finally, it cleans up the browser session. ```python import os import asyncio import requests from browser_use import Agent, Browser, ChatBrowserUse async def run_agent(): # Create Browser Cash session resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", }, json={}, ) resp.raise_for_status() data = resp.json() # Create Browser-Use browser with Browser Cash CDP URL browser = Browser(cdp_url=data["cdpUrl"]) llm = ChatBrowserUse() # Create and run agent agent = Agent( task="Find the current price of Bitcoin", llm=llm, browser=browser, ) result = await agent.run() # Cleanup requests.delete( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}"}, params={"sessionId": data["sessionId"]}, ) return result if __name__ == "__main__": result = asyncio.run(run_agent()) print(result) ``` -------------------------------- ### Create Browser Session with Custom Options (Python) Source: https://docs.browser.cash/docs/integrations/browser-use Initiates a Browser Cash session with specific configuration options, including country, browser type, and window size. The 'consumer_distributed' type is recommended for maximum stealth. ```python resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", }, json={ "country": "US", "type": "consumer_distributed", # Maximum stealth "windowSize": "1920x1080", }, ) ``` -------------------------------- ### Create Browser Session with Specific Type Source: https://docs.browser.cash/docs/features/node-selection Demonstrates how to create a browser session using a specified infrastructure type. Supports 'hosted' for data center reliability or 'consumer_distributed' for maximum stealth. Requires API key for authentication. ```typescript const session = await client.browser.session.create({ type: "hosted", }); ``` ```python resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", }, json={"type": "hosted"} ) session = resp.json() ``` ```bash curl -X POST https://api.browser.cash/v1/browser/session \ -H "Authorization: Bearer $BROWSER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"type": "hosted"}' ``` -------------------------------- ### GET /v1/browser/profiles Source: https://docs.browser.cash/docs/features/browser-profiles Retrieves a list of all saved browser profiles for the account. ```APIDOC ## GET /v1/browser/profiles ### Description Retrieves a list of all saved browser profiles for the account. ### Method GET ### Endpoint /v1/browser/profiles ### Parameters None ### Request Example ```bash curl https://api.browser.cash/v1/browser/profiles \ -H "Authorization: Bearer $BROWSER_API_KEY" ``` ### Response #### Success Response (200) - **profiles** (array) - A list of profile objects. - **profileId** (string) - The unique ID of the profile. - **name** (string) - The name of the profile. - **createdAt** (string) - The timestamp when the profile was created. #### Response Example ```json { "profiles": [ { "profileId": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", "name": "my-profile", "createdAt": "2025-12-19T18:58:03.000Z" } ] } ``` ``` -------------------------------- ### Configure API Keys for Browser-Use and Browser Cash Source: https://docs.browser.cash/docs/integrations/browser-use Sets up environment variables for API keys required by Browser-Use and Browser Cash. These keys are essential for authenticating and authorizing access to the respective services. ```env # .env BROWSER_USE_API_KEY=your-browser-use-key BROWSER_API_KEY=your-browser-cash-key ``` -------------------------------- ### Get Session Details Source: https://docs.browser.cash/docs/fundamentals/viewing-a-browser-session Retrieve detailed information about a specific browser session using its session ID. ```APIDOC ## Get Session Details ### Description Retrieve detailed information about a specific browser session. ### Method GET ### Endpoint `/v1/browser/session` ### Parameters #### Query Parameters - **sessionId** (string) - Required - The ID of the session to retrieve details for. ### Request Example ```bash curl -X GET "https://api.browser.cash/v1/browser/session?sessionId=sess_abc123xyz" \ -H "Authorization: Bearer $BROWSER_API_KEY" ``` ### Response #### Success Response (200) - **sessionId** (string) - The unique identifier for the session. - **status** (string) - The current status of the session (`active`, `stopped`, `failed`). - **servedBy** (string) - The node that is serving the session. - **createdAt** (string) - The timestamp when the session was created. - **stoppedAt** (string | null) - The timestamp when the session was stopped, or null if still active. - **cdpUrl** (string) - The WebSocket URL for connecting to the browser's CDP. #### Response Example ```json { "sessionId": "sess_abc123xyz", "status": "active", "servedBy": "node-us-east-1", "createdAt": "2024-01-15T10:30:00.000Z", "stoppedAt": null, "cdpUrl": "wss://cdp.browser.cash/sess_abc123xyz" } ``` ### Session Status Values | Status | Description | | --------- | -------------------------------------------- | | `active` | Session is running and accepting connections | | `stopped` | Session has been terminated | | `failed` | Session failed to start | ``` -------------------------------- ### Target a Specific Node for Browser Session Source: https://docs.browser.cash/docs/features/node-selection Shows how to create a browser session and then target the same node for subsequent sessions using the `servedBy` field. This ensures consistency by reusing the same infrastructure. Includes session creation, retrieval of the node ID, and subsequent session creation with the specified `nodeId`. ```typescript // Create first session const session1 = await client.browser.session.create(); console.log("Node:", session1.servedBy); // "node-us-east-abc123" // Stop when done await client.browser.session.stop({ sessionId: session1.sessionId }); // Later — target the same node const session2 = await client.browser.session.create({ nodeId: session1.servedBy, }); ``` ```python import os import requests headers = { "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", } # Create first session resp1 = requests.post( "https://api.browser.cash/v1/browser/session", headers=headers, json={} ) session1 = resp1.json() print("Node:", session1["servedBy"]) # "node-us-east-abc123" # Stop when done requests.delete( "https://api.browser.cash/v1/browser/session", headers=headers, params={"sessionId": session1["sessionId"]} ) # Later — target the same node resp2 = requests.post( "https://api.browser.cash/v1/browser/session", headers=headers, json={"nodeId": session1["servedBy"]} ) session2 = resp2.json() ``` -------------------------------- ### Manage Persistent Browser Profiles (Python) Source: https://docs.browser.cash/docs/integrations/browser-use Shows how to use persistent profiles to maintain login sessions across multiple agent runs. By setting `persist: True` with a profile name, subsequent sessions with the same profile name will be pre-logged into services. ```python import os import requests headers = { "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", } # First run — login resp = requests.post( "https://api.browser.cash/v1/browser/session", headers=headers, json={ "profile": {"name": "my-agent-profile", "persist": True} }, ) # Agent logs into a service... # Later runs — already logged in resp = requests.post( "https://api.browser.cash/v1/browser/session", headers=headers, json={ "profile": {"name": "my-agent-profile", "persist": True} }, ) ``` -------------------------------- ### Get Browser Session Details Source: https://docs.browser.cash/docs/fundamentals/viewing-a-browser-session Retrieve detailed information about a specific browser session using its `sessionId`. This operation requires authentication and returns session status, creation time, and the CDP URL. ```typescript const session = await client.browser.session.get({ sessionId: "sess_abc123xyz", }); console.log(session); ``` ```python import os import requests resp = requests.get( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}"}, params={"sessionId": "sess_abc123xyz"} ) session = resp.json() print(session) ``` ```cURL curl -X GET "https://api.browser.cash/v1/browser/session?sessionId=sess_abc123xyz" \ -H "Authorization: Bearer $BROWSER_API_KEY" ``` -------------------------------- ### Create Browser Session with Options Source: https://docs.browser.cash/docs/integrations/crawl4ai Initiates a Browser Cash browser session with specific options, such as country, browser type for maximum stealth, and window size. This allows for more control over the browsing environment. ```python resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {os.getenv('BROWSER_CASH_API_KEY')}", "Content-Type": "application/json", }, json={ "country": "US", "type": "consumer_distributed", # Maximum stealth "windowSize": "1920x1080", }, ) ``` -------------------------------- ### Manage Persistent Browser Profiles Source: https://docs.browser.cash/docs/integrations/playwright Demonstrates creating and using persistent browser profiles. The first run logs in and saves the profile, while subsequent runs start with the session already logged in. This requires the Browser Cash client and Playwright. ```typescript const session1 = await client.browser.session.create({ profile: { name: "my-account", persist: true }, }); const browser1 = await chromium.connectOverCDP(session1.cdpUrl); const page1 = await browser1.newPage(); // Login flow... await page1.goto("https://example.com/login"); await page1.fill("#email", "user@example.com"); await page1.fill("#password", "password"); await page1.click('button[type="submit"]'); await browser1.close(); await client.browser.session.stop({ sessionId: session1.sessionId }); // Later — session starts already logged in const session2 = await client.browser.session.create({ profile: { name: "my-account", persist: true }, }); ``` ```python import os import requests from playwright.sync_api import sync_playwright headers = { "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", } # First run — login and save profile resp1 = requests.post( "https://api.browser.cash/v1/browser/session", headers=headers, json={"profile": {"name": "my-account", "persist": True}} ) session1 = resp1.json() with sync_playwright() as p: browser1 = p.chromium.connect_over_cdp(session1["cdpUrl"]) page1 = browser1.new_page() # Login flow... page1.goto("https://example.com/login") page1.fill("#email", "user@example.com") page1.fill("#password", "password") page1.click('button[type="submit"]') browser1.close() # Stop session1 requests.delete( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}"}, params={"sessionId": session1["sessionId"]} ) # Later — session starts already logged in resp2 = requests.post( "https://api.browser.cash/v1/browser/session", headers=headers, json={"profile": {"name": "my-account", "persist": True}} ) session2 = resp2.json() ``` -------------------------------- ### Handle Connection Errors in Browser Automation (TypeScript, Python) Source: https://docs.browser.cash/docs/fundamentals/using-a-browser-session Demonstrates how to handle 'connection refused' errors, which may indicate an expired session. It includes logic to create a new session and retry the automation. This pattern is crucial for robust browser automation workflows. ```typescript try { const browser = await chromium.connectOverCDP(session.cdpUrl); // ... automation } catch (error) { if (error.message.includes("connection refused")) { // Session may have expired — create a new one const newSession = await client.browser.session.create(); // Retry with new session } } finally { await client.browser.session.stop({ sessionId: session.sessionId }); } ``` ```python api_key = os.getenv("BROWSER_API_KEY") headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", } try: browser = p.chromium.connect_over_cdp(session["cdpUrl"]) # ... automation except Exception as e: if "connection refused" in str(e).lower(): # Session may have expired — create a new one new_resp = requests.post( "https://api.browser.cash/v1/browser/session", headers=headers, json={} ) new_session = new_resp.json() browser = p.chromium.connect_over_cdp(new_session["cdpUrl"]) # Retry automation with new session else: raise finally: requests.delete( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {api_key}"}, params={"sessionId": session["sessionId"]} ) ``` -------------------------------- ### Stop Browser Session (TypeScript, Python, cURL) Source: https://docs.browser.cash/docs/fundamentals/managing-a-browser-session Demonstrates how to stop an active browser session to clean up resources and avoid ongoing billing. This is crucial for managing automation tasks efficiently. The examples show the API call in TypeScript, Python, and cURL. ```typescript const result = await client.browser.session.stop({ sessionId: "sess_abc123xyz", }); console.log(result); ``` ```python import os import requests resp = requests.delete( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}"}, params={"sessionId": "sess_abc123xyz"} ) print(resp.json()) ``` ```bash curl -X DELETE "https://api.browser.cash/v1/browser/session?sessionId=sess_abc123xyz" \ -H "Authorization: Bearer $BROWSER_API_KEY" ``` -------------------------------- ### POST /v1/browser/session Source: https://docs.browser.cash/docs/integrations/browser-use Creates a new browser session. This session can be configured with various options such as country, type, window size, and persistent profiles for maintaining login states across multiple agent runs. ```APIDOC ## POST /v1/browser/session ### Description Creates a new browser session. This session can be configured with various options such as country, type, window size, and persistent profiles for maintaining login states across multiple agent runs. ### Method POST ### Endpoint /v1/browser/session ### Parameters #### Query Parameters None #### Request Body - **country** (string) - Optional - The country from which the session should originate. - **type** (string) - Optional - The type of session to create. Example: "consumer_distributed" for maximum stealth. - **windowSize** (string) - Optional - The desired window size for the browser, e.g., "1920x1080". - **profile** (object) - Optional - Configuration for persistent profiles. - **name** (string) - Required - The name of the profile. - **persist** (boolean) - Required - Whether to persist the profile across sessions. ### Request Example ```json { "country": "US", "type": "consumer_distributed", "windowSize": "1920x1080", "profile": { "name": "my-agent-profile", "persist": true } } ``` ### Response #### Success Response (200) - **sessionId** (string) - The unique identifier for the created browser session. - **cdpUrl** (string) - The Chrome DevTools Protocol URL for connecting to the browser session. #### Response Example ```json { "sessionId": "some-session-id", "cdpUrl": "ws://127.0.0.1:9222/devtools/page/some-page-id" } ``` ``` -------------------------------- ### Browser Session Lifecycle Management (TypeScript, Python) Source: https://docs.browser.cash/docs/fundamentals/managing-a-browser-session Provides a robust way to manage browser sessions using a context manager pattern. This ensures that sessions are always stopped after use, even if errors occur during automation. Includes examples for TypeScript and Python. ```typescript async function withSession( fn: (session: Session) => Promise ): Promise { const session = await client.browser.session.create(); try { return await fn(session); } finally { await client.browser.session.stop({ sessionId: session.sessionId }); } } // Usage await withSession(async (session) => { const browser = await chromium.connectOverCDP(session.cdpUrl); // ... automation await browser.close(); }); ``` ```python from contextlib import contextmanager @contextmanager def browser_session(**opts): api_key = os.getenv("BROWSER_API_KEY") resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", }, json=opts ) session = resp.json() try { yield session } finally { requests.delete( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {api_key}"}, params={"sessionId": session["sessionId"]} ) } // Usage with browser_session() as session: browser = p.chromium.connect_over_cdp(session["cdpUrl"]) # ... automation browser.close() ``` -------------------------------- ### Initialize the Session Pool Source: https://docs.browser.cash/docs/fundamentals/concurrent-browser-sessions Initializes the SessionPool, creating the specified number of browser sessions and preparing them for use. This method must be called before acquiring sessions. ```typescript const pool = new SessionPool({ /* options */ }); await pool.init(); ``` -------------------------------- ### Python: Create Browser Cash Session with Options Source: https://docs.browser.cash/docs/integrations/selenium Shows how to create a Browser Cash session with specific options such as country, type, and window size by sending a POST request to the Browser Cash API. ```python resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", }, json={ "country": "US", "type": "hosted", "windowSize": "1920x1080" } ) ``` -------------------------------- ### Create and Manage Browser Sessions (TypeScript, Python, cURL) Source: https://docs.browser.cash/docs/introduction/what-is-browser-cash Demonstrates how to create, connect to, and stop managed browser sessions using Browser Cash. Supports TypeScript with Playwright, Python with Playwright, and cURL for direct API interaction. Requires an API key for authentication. ```typescript import BrowsercashSDK from "@browsercash/sdk"; import { chromium } from "playwright"; const client = new BrowsercashSDK({ apiKey: process.env.BROWSER_API_KEY }); const session = await client.browser.session.create(); const browser = await chromium.connectOverCDP(session.cdpUrl); // ... automate await client.browser.session.stop({ sessionId: session.sessionId }); ``` ```python import os import requests from playwright.sync_api import sync_playwright # Create session resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", }, json={} ) session = resp.json() # Connect and automate with sync_playwright() as p: browser = p.chromium.connect_over_cdp(session["cdpUrl"]) # ... automate browser.close() # Stop session requests.delete( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}"}, params={"sessionId": session["sessionId"]} ) ``` ```bash # Create session curl -X POST https://api.browser.cash/v1/browser/session \ -H "Authorization: Bearer $BROWSER_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' # Response: { "sessionId": "...", "cdpUrl": "wss://..." } # Connect using cdpUrl with any CDP client ``` -------------------------------- ### POST /v1/browser/session Source: https://docs.browser.cash/docs/features/browser-profiles Creates a new browser session with an optional named profile. If 'persist' is true, the browser state will be saved when the session stops. ```APIDOC ## POST /v1/browser/session ### Description Creates a new browser session with an optional named profile. If 'persist' is true, the browser state will be saved when the session stops. ### Method POST ### Endpoint /v1/browser/session ### Parameters #### Request Body - **profile** (object) - Optional - Configuration for the browser profile. - **name** (string) - Required - Unique identifier for the profile. - **persist** (boolean) - Required - Set to `true` to save state when session stops. ### Request Example ```json { "profile": { "name": "my-profile", "persist": true } } ``` ### Response #### Success Response (200) - **session** (object) - Details of the created browser session. - **sessionId** (string) - The unique identifier for the session. - **url** (string) - The URL to connect to the session. - **profile** (object) - Information about the profile used for the session. - **name** (string) - The name of the profile. - **persist** (boolean) - Whether the profile state is persisted. #### Response Example ```json { "sessionId": "sess_abc123", "url": "wss://browser.browser.cash/sess_abc123", "profile": { "name": "my-profile", "persist": true } } ``` ``` -------------------------------- ### Browser Cash Session Options (TypeScript) Source: https://docs.browser.cash/docs/integrations/stagehand Demonstrates creating a Browser Cash session with specific options such as country, session type, window size, and profile persistence. These options allow for customization of the browser environment for automation tasks. ```typescript const session = await client.browser.session.create({ country: 'US', type: 'consumer_distributed', windowSize: '1920x1080', profile: { name: 'stagehand-session', persist: true }, }); ``` -------------------------------- ### Create Browser Session with Profile Source: https://docs.browser.cash/docs/features/browser-profiles Initiates a new browser session with a named profile, allowing for state persistence. The browser state is saved when the session stops if 'persist' is set to true. Dependencies include the Browser.cash client library. ```typescript const session = await client.browser.session.create({ profile: { name: "my-profile", persist: true, }, }); // Do your automation... // Browser state will be saved when session stops ``` ```python resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {os.getenv('BROWSER_API_KEY')}", "Content-Type": "application/json", }, json={ "profile": { "name": "my-profile", "persist": True } } ) session = resp.json() ``` ```curl curl -X POST https://api.browser.cash/v1/browser/session \ -H "Authorization: Bearer $BROWSER_API_KEY" \ -H "Content-Type: application/json" \ -d '{"profile": {"name": "my-profile", "persist": true}}' ``` -------------------------------- ### Cleanup Best Practices Source: https://docs.browser.cash/docs/fundamentals/managing-a-browser-session Implement best practices for managing browser sessions, ensuring they are always stopped after use. ```APIDOC ## Cleanup Best Practices It is recommended to use a `try...finally` block or a context manager to ensure that sessions are always stopped, even if errors occur during automation. ### Example (TypeScript) ```typescript async function withSession(fn: (session: Session) => Promise): Promise { const session = await client.browser.session.create(); try { return await fn(session); } finally { await client.browser.session.stop({ sessionId: session.sessionId }); } } // Usage await withSession(async (session) => { const browser = await chromium.connectOverCDP(session.cdpUrl); // ... automation await browser.close(); }); ``` ### Example (Python) ```python from contextlib import contextmanager @contextmanager def browser_session(**opts): api_key = os.getenv("BROWSER_API_KEY") resp = requests.post( "https://api.browser.cash/v1/browser/session", headers={ "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", }, json=opts ) session = resp.json() try: yield session finally: requests.delete( "https://api.browser.cash/v1/browser/session", headers={"Authorization": f"Bearer {api_key}"}, params={"sessionId": session["sessionId"]} ) # Usage with browser_session() as session: browser = p.chromium.connect_over_cdp(session["cdpUrl"]) # ... automation browser.close() ``` ``` -------------------------------- ### Run Python Script with uv Source: https://docs.browser.cash/docs/integrations/crawl4ai Executes the main Python script using the uv run command. This ensures the script runs within the environment managed by uv. ```bash uv run main.py ```