← Blog

BLOG

Playwright Connect to Existing Browser: A Practical Guide

Learn how to use Playwright to connect to an existing browser session via CDP, and why hosted Chromium simplifies persistent browser automation.

August 22, 20269 min readRemote Browser

# Playwright Connect to Existing Browser: A Practical Guide

Playwright is the de facto standard for browser automation, but its default model assumes you launch a fresh browser instance for each script. When you need to connect to an existing browser—one that holds a logged-in session, has state in memory, or is already running on a remote machine—the standard playwright.chromium.launch() call won't cut it. This guide explains how to use Playwright's connectOverCDP method to attach to a live browser, the production trade-offs involved, and why a hosted Chromium runtime often beats managing this infrastructure yourself.

Why Connect to an Existing Browser?

The primary use case for connecting to an existing browser is session persistence. A standard Playwright launch creates a clean, ephemeral profile. Every cookie, localStorage entry, and session token is lost when the script ends. For AI agents that need to perform multi-step tasks—logging into a portal, navigating, extracting data, then performing an action—losing the session between steps is a dealbreaker.

Connecting to an existing browser solves this by letting you attach to a browser that has already been configured with the right profile, proxies, and session state. This is particularly relevant for:

  • AI agents that need to maintain context across multiple tool calls.
  • Long-running automation that must survive script restarts.
  • Debugging where you want to inspect a live browser state.
  • Cloud workers that need to share a single browser session across multiple processes.

How Playwright Connects to an Existing Browser

Playwright provides a dedicated API for this: chromium.connectOverCDP(). This method connects to a browser that is already running and exposes a Chrome DevTools Protocol (CDP) endpoint. Here is a minimal TypeScript example:

import { chromium } from 'playwright';

async function connectToExistingBrowser() {
  // The CDP endpoint URL of the running browser.
  // For a local browser, this is typically http://localhost:9222
  const browser = await chromium.connectOverCDP('http://localhost:9222');

  // Get the default context (the one the browser was launched with).
  const defaultContext = browser.contexts()[0];
  const page = await defaultContext.newPage();

  await page.goto('https://example.com');
  console.log(await page.title());

  // Do not close the browser; we only close the connection.
  await browser.close();
}

connectToExistingBrowser();

The critical detail here is that browser.close() in this context does not terminate the browser process. It only disconnects the Playwright client. The underlying Chromium instance remains alive, retaining its session state. This is the core mechanism for keeping a browser session alive across multiple cloud workers or script executions.

Launching a Browser with a CDP Endpoint

To connect to a browser, that browser must be running with a remote debugging port. Locally, you would launch Chromium with the --remote-debugging-port=9222 flag. In a hosted environment, the provider typically exposes this endpoint for you.

The Problem with Local connectOverCDP

While connectOverCDP works, it introduces significant operational overhead when you move beyond a single local machine:

  1. Process Management: You must ensure the browser process stays alive. If the machine reboots or the process crashes, your session is gone.
  2. Network Exposure: Exposing a CDP endpoint on a network port is a security risk. You need authentication and TLS to prevent unauthorized access.
  3. Scalability: Running a persistent browser on a single machine creates a bottleneck. You cannot easily distribute the load across multiple workers.
  4. State Fragility: A browser process is a heavy, stateful object. If your automation code has a bug that crashes the renderer, you lose the session.

For a single developer debugging a script, local connectOverCDP is fine. For production AI agents or high-volume automation, it becomes a liability.

Hosted Chromium: The Production Alternative

This is where a hosted browser runtime like Remote Browser fits. Instead of managing a long-lived browser process yourself, you request a browser session from an API. The service handles process lifecycle, network security, and scaling. Your code connects via CDP or a standard Playwright/Puppeteer driver.

The table below compares the two approaches:

FeatureLocal connectOverCDPHosted Chromium (Remote Browser)
Session PersistenceManual; depends on process uptimeManaged; sessions persist across API calls
InfrastructureYou manage the browser process and networkProvider manages the browser fleet
ScalingLimited to one machineHorizontal scaling across cloud workers
SecurityYou must secure the CDP portProvider handles authentication and network isolation
DebuggingRequires local access or port forwardingLive viewer and session replay tools
Proxy SupportManual configurationConfigurable via API or dashboard
Failure RecoveryManual restart; session lossManaged recovery; session state preserved in profiles

How to Keep Browser Sessions Alive Across Multiple Cloud Workers

The core challenge with cloud workers is that they are often stateless and ephemeral. A worker spins up, executes a task, and shuts down. If your automation relies on a browser session, you need a way to persist that session outside the worker's lifecycle.

With a hosted runtime, the pattern is straightforward:

  1. Create a Session: Your worker calls the Remote Browser API to create a new browser session. The API returns a session ID and a connection URL.
  2. Connect and Execute: The worker uses connectOverCDP (or a standard Playwright driver) to connect to that URL and execute the task.
  3. Detach: The worker disconnects from the browser but does not destroy it. The session remains active in the cloud.
  4. Reconnect: A different worker, or the same one after a restart, connects to the same session ID to continue the task.

This decouples the browser's lifecycle from the worker's lifecycle. The session is the source of truth, not the process.

Playwright Remote Browser: Using the Driver

If you are using the Playwright library, you can connect to a hosted browser using the standard connectOverCDP method with the provided endpoint. The code looks almost identical to the local example, but the URL points to the hosted service.

import { chromium } from 'playwright';

async function connectToHostedBrowser(cdpUrl: string) {
  const browser = await chromium.connectOverCDP(cdpUrl);
  const context = browser.contexts()[0];
  const page = await context.newPage();

  // Your automation logic here.
  await page.goto('https://example.com');

  // Disconnect without closing the hosted browser.
  await browser.close();
}

The advantage is that you do not need to worry about the browser's underlying infrastructure. The provider ensures the browser is running, is reachable, and has the correct profile loaded.

Browser Control and In-App Browser Skills

For AI agents, the ability to control a browser is often framed as a "skill." The agent receives a tool definition that allows it to navigate, click, and type. The implementation detail—whether it uses Playwright, CDP directly, or a higher-level API—is abstracted away.

When building an agent that uses a browser, you have two choices:

  1. Local Execution: The agent runs on a machine with a browser installed. This is simple but limits the agent to a single machine and makes scaling difficult.
  2. Remote Execution: The agent calls a remote browser API. This allows the agent to run anywhere (serverless, Kubernetes, etc.) while the browser runs in a managed environment.

The remote approach is more robust for production because it separates the compute (the agent's LLM calls) from the I/O (the browser). This separation allows you to scale the agent and the browser independently.

Web Automation API vs. Direct CDP

You can interact with a remote browser in two primary ways:

  • Direct CDP: You use the raw Chrome DevTools Protocol to send commands. This gives you maximum control but requires you to handle protocol details and state management.
  • High-Level API: You use a library like Playwright or Puppeteer, or a REST API provided by the browser runtime. This abstracts away protocol details and is generally more productive.

For most use cases, a high-level API is the right choice. It is easier to write, debug, and maintain. Direct CDP is useful for specific low-level operations that the libraries do not expose, but it is not a good foundation for a large automation suite.

What Is an Agent Browser?

The term "agent browser" refers to a browser runtime designed specifically for AI agents. Unlike a standard browser, an agent browser is built to be controlled programmatically, to persist state across sessions, and to be observable (e.g., via a live viewer). It is infrastructure, not a user-facing product.

Key features of an agent browser include:

  • Session Management: Create, resume, and destroy sessions via API.
  • Profile Persistence: Store cookies, localStorage, and other state so sessions survive restarts.
  • Observability: Provide a live view or screen recording for debugging.
  • Stealth Settings: Configurable browser settings to reduce the chance of bot detection.
  • Proxy Integration: Route traffic through specific IPs or geographies.

Production Criteria for Browser Automation

When evaluating a browser automation solution, consider the following criteria:

  1. Reliability: How often does the browser crash or hang? What is the recovery process?
  2. Session Persistence: Can you save and restore state? Is the session tied to a specific process?
  3. Scalability: Can you run hundreds or thousands of sessions concurrently?
  4. Observability: Can you see what the browser is doing in real-time? Can you replay past sessions?
  5. Security: How is access to the browser controlled? Is the connection encrypted?
  6. Cost: Is the pricing model predictable? Are there hidden costs for bandwidth or storage?

Browser Benchmarking and Performance

Performance is a critical factor. A slow browser session can cause timeouts and failed tasks. When benchmarking a browser automation solution, look at:

  • Time to First Byte (TTFB): How quickly does the browser respond to a navigation request?
  • Session Startup Time: How long does it take to create a new browser session?
  • Memory Footprint: How much memory does each session consume?
  • Concurrency Limits: How many sessions can run in parallel without degradation?

Hosted solutions often have an advantage here because they can pre-warm browser instances and use optimized hardware. However, you should always benchmark against your specific workload.

Conclusion

Playwright's connectOverCDP is a powerful tool for connecting to an existing browser, but it is only the first step. For production workloads—especially AI agents that need persistent sessions across cloud workers—you need a managed runtime that handles the infrastructure for you.

Remote Browser provides that runtime. It offers hosted Chromium sessions with CDP access, Playwright compatibility, persistent profiles, and a live viewer for debugging. Instead of managing fragile browser processes, you treat the browser as an API resource.

To get started, explore the Remote Browser documentation to understand the API, or check out our guide on remote browsers for AI agents to see how this fits into an agent architecture. If you are evaluating costs, our pricing page has the latest details.

For a deeper dive into the technical protocol, refer to the official Chrome DevTools Protocol documentation or the Playwright CDP guide.

The key takeaway is this: connecting to an existing browser is a solved problem. The real challenge is keeping that browser alive, secure, and scalable. That is where a hosted runtime earns its keep.