← Blog

BLOG

Playwright ConnectOverCDP: Drive Remote Chrome Instances

Playwright connectOverCDP lets you attach to remote Chrome. Learn how Remote Browser's hosted Chromium makes CDP connections production-ready.

September 2, 202610 min readRemote Browser

# Playwright ConnectOverCDP: Drive Remote Chrome Instances

Playwright's connectOverCDP method is the standard way to attach your automation code to an already-running Chrome instance. Instead of launching a fresh browser process, you connect to one that's already alive—whether it's running locally, in a Docker container, or on a remote host. This capability is essential for AI agents, long-running automation jobs, and teams that need to inspect or control a browser session that they didn't start themselves.

The challenge is that connectOverCDP only works if you have a Chrome instance with the Chrome DevTools Protocol (CDP) endpoint exposed and accessible. Setting that up reliably in production—with persistent sessions, proper networking, and scaling—is where most teams get stuck. This guide explains how Playwright connectOverCDP works, why you'd use it, and how a hosted Chromium runtime like Remote Browser removes the infrastructure burden.

What Is Playwright ConnectOverCDP?

connectOverCDP is a static method on the playwright object. It establishes a connection to an existing Chromium-based browser over the Chrome DevTools Protocol. Unlike chromium.launch(), which spawns a new browser process, connectOverCDP attaches to a browser that is already running and listening on a debugging port.

import { chromium } from 'playwright';

// Connect to an existing Chrome instance via CDP
const browser = await chromium.connectOverCDP('http://localhost:9222');

// The default context contains the existing pages
const defaultContext = browser.contexts()[0];
const page = defaultContext.pages()[0];

// Or create a new page in the existing browser
const newPage = await defaultContext.newPage();
await newPage.goto('https://example.com');
console.log(await newPage.title());

await browser.close();

The CDP endpoint is typically an HTTP URL like http://localhost:9222. When Chrome launches with --remote-debugging-port=9222, it exposes a REST API and a WebSocket endpoint that CDP clients can use to control it.

Key Differences from launch()

Featurechromium.launch()chromium.connectOverCDP()
Browser lifecyclePlaywright starts and stops the browserBrowser runs independently; Playwright attaches/detaches
Session persistenceLost when script endsBrowser state persists after script ends
Use caseShort-lived test runsLong-running agents, manual debugging, shared sessions
Browser visibilityHeadless by defaultCan connect to headed browsers with a visible UI
Multi-clientSingle client controls the browserMultiple clients can connect to the same browser
InfrastructureLocal process managementRequires a reachable CDP endpoint

The most important distinction is lifecycle. With launch(), when your Node.js process exits, the browser dies. With connectOverCDP(), the browser keeps running. This makes it the right choice for scenarios where you need the browser to outlive your script—or where you want to inspect what an agent is doing in real time.

Why Use ConnectOverCDP in Production?

There are several production scenarios where connectOverCDP is the correct architectural choice.

1. Keeping Browser Sessions Alive Across Workers

Serverless functions and cloud workers are stateless. Each invocation starts fresh, does its work, and shuts down. If your AI agent or automation script needs a persistent browser session—with logged-in state, cookies, or local storage—you can't rely on the worker to maintain it.

By running a dedicated Chrome instance in a remote location and connecting to it via CDP, you decouple the browser's lifecycle from your worker's lifecycle. Worker A can log into a service, disconnect, and Worker B can pick up the same session hours later. This is the pattern behind remote browsers for AI agents.

2. Giving AI Agents Browser Access in Production

AI agents that browse the web need a controlled, observable browser environment. When an agent runs in a sandboxed environment, it can't launch a local browser with a visible UI. Connecting to a remote browser over CDP gives the agent full browser access while keeping the actual Chromium instance in a managed environment.

You can watch the agent work through a live viewer, intervene if it goes off track, and maintain persistent profiles across agent runs. This is the core use case for remote browser online infrastructure.

3. Scaling Browser Workloads Reliably

Running many browser instances on a single machine can lead to resource contention and flaky behavior. A hosted browser service handles the scaling problem for you. You get a CDP endpoint for each browser session, and you connect to it with connectOverCDP from any environment that has network access.

The Production Problem: Managing CDP Endpoints

While connectOverCDP is simple in principle, production deployment introduces several complications.

Networking and Accessibility

For connectOverCDP to work, the Chrome instance must be reachable from your automation code. If your code runs on a cloud worker and your Chrome instance runs on your laptop, you need to expose the debugging port through a tunnel or a public endpoint. This creates security risks and operational overhead.

Session Isolation

When you connect to a browser over CDP, you're sharing that browser with anyone else who knows the endpoint. In production, you need session isolation—each agent or test run should have its own browser instance with its own profile, cookies, and storage.

Browser Health and Restarts

Chrome instances crash. They run out of memory. They get stuck on unresponsive pages. When you manage your own browser fleet, you need to build health checks, restart logic, and cleanup processes. This is infrastructure work that distracts from your core automation logic.

Persistent Profiles

For many automation workloads, you need the browser to remember state between connections. This means storing the browser profile (cookies, local storage, IndexedDB) and attaching it to the browser when it starts. Doing this reliably across multiple browser instances requires a profile management system.

How Remote Browser Solves the CDP Infrastructure Problem

Remote Browser provides hosted Chromium sessions that you connect to using standard Playwright connectOverCDP calls. It handles the infrastructure so you can focus on your automation logic.

What You Get

  • A CDP endpoint for every browser session: Each session gets a unique URL that you can pass directly to connectOverCDP.
  • Persistent profiles: Sessions can be configured to save and restore browser state, so your agents pick up where they left off.
  • Live debugging: You can watch the browser session in real time through a web-based viewer, which is invaluable for debugging AI agents.
  • Configurable browser settings: Adjust proxy settings, viewport, user agent, and other browser properties per session.
  • Session isolation: Each session runs in its own isolated Chromium instance, so one agent's actions don't affect another's.

Connecting to a Remote Browser Session

Here's what the code looks like when you connect to a Remote Browser session:

import { chromium } from 'playwright';

// The CDP endpoint for your Remote Browser session
// You get this from the Remote Browser dashboard or API
const cdpUrl = 'wss://remote-browser.dev/cdp/session_abc123';

// Connect to the hosted Chromium instance
const browser = await chromium.connectOverCDP(cdpUrl);

// Get the default context (this is where your persistent profile lives)
const context = browser.contexts()[0];

// Use the browser like any other Playwright browser
const page = await context.newPage();
await page.goto('https://news.ycombinator.com');
await page.click('text=Login');

// The session stays alive after you disconnect
await browser.close();

The key difference is that browser.close() disconnects your client from the browser—it doesn't terminate the Chromium instance. The session remains available for the next connection, with all its state intact.

Comparing Hosted CDP vs. Self-Managed Chrome

CriterionSelf-Managed ChromeRemote Browser Hosted Chromium
Setup timeInstall Chrome, configure flags, expose portCreate a session via API or dashboard
ScalingManual; each machine has limitsAutomatic; sessions provisioned on demand
Session persistenceRequires custom profile managementBuilt-in persistent profiles
MonitoringBuild your own health checksLive viewer and session status API
Network exposureYou handle security and tunnelingManaged, authenticated endpoints
Browser versionsYou maintain and updateManaged by the service
CostServer costs + engineering timeUsage-based; see pricing

The trade-off is clear: if you're running a handful of scripts occasionally, self-managed Chrome is fine. If you're running AI agents, continuous automation, or any workload where browser uptime matters, the engineering cost of self-managing CDP endpoints quickly exceeds the cost of a hosted service.

Production Criteria for ConnectOverCDP Workloads

When evaluating whether connectOverCDP is right for your workload—and whether you should host the browser yourself or use a service—consider these criteria.

Session Longevity

How long does your browser session need to live? If your script completes in seconds and exits, launch() is simpler. If your agent runs for hours or needs to persist across multiple script invocations, connectOverCDP is the right choice.

State Requirements

Does your automation depend on logged-in state, cookies, or local storage? If so, you need a persistent profile. Decide whether you'll manage profile directories yourself or rely on a service that handles it.

Observability

Can you debug your automation when it fails? With a local browser, you can watch it run. With a remote browser, you need a live viewer or video recording. Without observability, debugging AI agent failures becomes guesswork.

Concurrency and Isolation

How many browser sessions do you need simultaneously? Can they share a browser instance, or do they need isolation? Sharing a browser via CDP is possible but risky—one script's page.goto() can interfere with another's. For production workloads, isolated sessions are safer.

Network Topology

Where does your automation code run, and where does the browser run? If they're in different networks, you need a reachable CDP endpoint. Consider whether you want to manage that network exposure yourself or use a service with authenticated endpoints.

Common Pitfalls with ConnectOverCDP

Even with a hosted service, there are pitfalls to avoid.

Assuming the Default Context Is Empty

When you connect to an existing browser, it may already have pages open. The default context isn't necessarily empty. Always check browser.contexts() and decide whether to use an existing page or create a new one.

Not Handling Disconnects Gracefully

Network connections drop. Your automation code should handle browser.close() and reconnection logic. If your script crashes, the remote browser session should survive and be reconnectable.

Ignoring Session Cleanup

Persistent sessions accumulate state. If you're running many automation tasks, you need a strategy for resetting profiles or creating fresh sessions periodically. Stale sessions can cause unexpected behavior.

Confusing close() with disconnect()

In Playwright, browser.close() on a connected browser disconnects the client. It doesn't shut down the remote browser. If you want to terminate the remote session, you need to use the service's API or dashboard.

When to Use Playwright ConnectOverCDP vs. Alternatives

connectOverCDP is not always the right tool. Here's a quick decision guide.

Use ConnectOverCDP When:

  • You need to attach to a browser that's already running
  • You want to inspect or debug a live session
  • You need the browser to persist beyond your script's lifetime
  • You're building an AI agent that needs a controlled browser environment
  • You want to share a browser session across multiple scripts or workers

Use Launch() When:

  • Your script is short-lived and self-contained
  • You don't need persistent state between runs
  • You're running parallel tests that each need a fresh browser
  • You don't need to observe the browser while it runs

Use a Browser Automation API When:

  • You want to avoid managing Playwright infrastructure entirely
  • You need browser sessions on demand without provisioning servers
  • You want built-in session management, profiles, and live debugging
  • You're building an AI agent and want to focus on agent logic, not browser plumbing

For the last case, a web automation API or remote control browser service abstracts away the CDP details entirely. You send a task, and the service handles browser provisioning, execution, and teardown.

Conclusion

Playwright connectOverCDP is a powerful method for attaching to existing Chrome instances. It's the right choice for AI agents, persistent automation sessions, and any workload where the browser must outlive your script. The production challenge is managing the CDP endpoints, session state, and browser fleet—infrastructure that most teams don't want to build themselves.

Remote Browser provides hosted Chromium sessions with CDP endpoints that work seamlessly with Playwright's connectOverCDP. You get persistent profiles, live debugging, session isolation, and configurable browser settings without managing browser infrastructure. This lets you focus on what matters: your automation logic, your AI agent's task completion, and your product's reliability.

To get started, check the documentation for API details, or review pricing to understand session costs. If you're building AI agents that need reliable browser access, understanding connectOverCDP is the first step—and using a hosted runtime is the last infrastructure decision you'll need to make.

For more technical details on the Chrome DevTools Protocol, refer to the official CDP documentation.