Connecting Playwright to an Existing Browser

Connect Playwright to a live browser to speed up debugging, reuse sessions, and streamline your local automation process.

Get Started free
Connecting Playwright to an Existing Browser
Home Guide Connecting Playwright to an Existing Browser

Connecting Playwright to an Existing Browser

Have you ever been in the middle of debugging a Playwright script and thought, “Why do I have to relaunch the browser every single time?”

I faced this recently while working on a complex flow. My Chrome was already in the perfect state—cookies loaded, dev tools open, everything ready—yet Playwright kept spinning up a fresh instance on every run.

It slowed the workflow and disrupted the entire debugging rhythm.

From my experience—and conversations with other automation engineers—about 30–40% of debugging time often goes into rebuilding browser state again and again.

That made me wonder:

  • Why restart the browser when it’s already open and ready?
  • Why lose cookies and state on every run?
  • Is there a way to connect Playwright to my existing browser?

These questions led me to explore Playwright’s ability to connect to an existing browser instance-a feature many testers underestimate, but one that drastically improved my debugging speed.

Overview

Connecting Playwright to an Existing Browser

Playwright allows you to attach to a browser that’s already running, letting you reuse the current session, cookies, tabs, and debugging state. This is especially useful when you want to avoid relaunching the browser repeatedly during development.

Steps to Connect Playwright to an Existing Browser

  • Start Chrome/Edge with the –remote-debugging-port enabled (e.g., 9222).
  • Open http://localhost:9222/json/version to get the webSocketDebuggerUrl.
  • Use chromium.connectOverCDP() in Playwright to attach to that running browser.
  • Create a new context (or reuse an existing one) within that connected browser.
  • Open a new page or interact with already opened tabs as needed.

In this article, I’ll walk you through exactly how I solved this problem, how Playwright’s connection mechanisms work, and why this technique can save you hours during test development.

Understanding Playwright’s Browser Connection Mechanism

By default, Playwright launches a fresh, isolated browser instance every time a script runs. This ensures clean tests, but it also means losing any existing state, open tabs, or debugging setup you already have.

To overcome this, Playwright provides a way to attach to a browser that’s already running, allowing automation to plug into your active session instead of starting over.

At the core of this mechanism is the idea that Playwright can communicate with an existing browser through an exposed debugging interface. When a browser runs with debugging enabled, it opens a communication channel that Playwright can connect to.

Once connected, your script can interact with the browser just as if Playwright had launched it itself, opening pages, reading current tabs, or reusing the live session.

This capability is especially powerful for debugging, stateful testing, and speeding up development because it removes the need to rebuild the browser environment every time you run a script.

And once you’ve streamlined your local debugging with Playwright’s connected-browser mode, BrowserStack Automate helps you validate the same flows at scale—on real browsers, with video logs, network insights, and live debugging to speed up iteration.

Playwright Testing

Methods to Connect to an Existing Browser

Playwright provides two main approaches to attach to a browser that’s already running. Both methods rely on the browser exposing a debugging interface that Playwright can communicate with.

1. Using a WebSocket Endpoint

When a browser is launched with remote debugging enabled, it exposes a WebSocket endpoint, which allows external tools to connect to it.

Key points:

  • The browser opens a communication channel that Playwright can attach to.
  • Playwright uses this endpoint to control an already running browser.
  • Ideal when you want to reuse active tabs, cookies, or logged-in sessions.
  • Works across Chromium-based browsers that expose a WebSocket debugger URL.

Best suited for: Lightweight debugging scenarios where you primarily want to reuse existing tabs or sessions without needing deep browser introspection.

2. Using Chrome DevTools Protocol (CDP)

Chromium browsers natively support the Chrome DevTools Protocol, which powers DevTools, Lighthouse, and many automation tools.

Key points:

  • Playwright can connect directly to an existing Chromium instance via CDP.
  • Provides deeper access to browser internals (contexts, pages, debugging tools).
  • Great for debugging workflows, performance analysis, and session reuse.
  • Supported by Chrome, Edge, Brave, and any Chromium-based browser.

Best suited for: More advanced debugging where you need detailed browser insights, better control of contexts/pages, or deeper visibility into browser behavior.

Step-by-Step Setup for Existing Browser Connection

Before writing any Playwright code, you first need to prepare the browser so Playwright can attach to it. Here’s the exact flow you can follow.

Step 1: Launch the Browser with Remote Debugging Enabled

Start Chrome or Edge manually with a remote debugging port (for example, 9222).

Windows (Chrome):

chrome.exe –remote-debugging-port=9222

Windows (Edge):

msedge.exe –remote-debugging-port=9222

macOS (Chrome):

/Applications/Google Chrome.app/Contents/MacOS/Google Chrome –remote-debugging-port=9222

Linux (Chrome):

google-chrome –remote-debugging-port=9222

Step 2: Verify the Debugging Endpoint

Once the browser is running with debugging enabled:

1. Open a new tab and go to:

http://localhost:9222/json/version

2. Look for:

  • webSocketDebuggerUrl → used when connecting via WebSocket
  • Other metadata about the running browser instance

This URL is your bridge between Playwright and the existing browser.

Step 3: Configure Playwright to Connect

In your Playwright script, instead of chromium.launch(), you’ll:

  • Use CDP URL (for Chromium-based browsers), e.g.

chromium.connectOverCDP(‘http://localhost:9222’);

  • Or use the WebSocket debugger URL from webSocketDebuggerUrl if you prefer the WebSocket approach.

At this point, Playwright is now attached to the browser you manually started.

Step 4: Create or Reuse a Browser Context

Once connected:

  • Create a new context to keep automation separate from your manual tabs, or
  • Inspect and reuse existing contexts/pages if your use case needs the live state.

Typical actions here include:

  • Creating a new page
  • Navigating to URLs
  • Interacting with elements in the already-running browser session

Step 5: Start Debugging and Iterating

With the connection in place, you can now:

  • Run scripts without relaunching the browser each time
  • Reuse logged-in sessions and existing cookies
  • Keep DevTools open while Playwright controls the same browser

This setup turns your usual “launch → run → close” loop into a much faster attach → debug → tweak workflow.

Playwright Code Example: Connecting to an Existing Browser

Once your browser is running with remote debugging enabled and you’ve retrieved the webSocketDebuggerUrl or CDP endpoint, you can attach Playwright directly to that live browser. Below are simple examples demonstrating both approaches-CDP and WebSocket-so you can choose the one that fits your workflow.

1. Connect Using Chrome DevTools Protocol (CDP)

This is the most common and stable method when working with Chromium-based browsers.

const { chromium } = require(‘@playwright/test’);

(async () => {
// Connect to the existing browser instance
const browser = await chromium.connectOverCDP(‘http://localhost:9222’);

// Create a new context (optional but recommended)
const context = await browser.newContext();

// Open a new page
const page = await context.newPage();
await page.goto(‘https://example.com’);

console.log(‘Connected successfully and navigated!’);
})();

Why this is useful:

  • Seamlessly connect to a manually launched browser
  • Reuse logged-in sessions
  • Keep DevTools open while automating

2. Connect Using the WebSocket Debugger URL

If you grabbed the webSocketDebuggerUrl from http://localhost:9222/json/version, you can connect like this:

const { chromium } = require(‘@playwright/test’);

(async () => {
const browser = await chromium.connect({
wsEndpoint: ‘ws://localhost:9222/devtools/browser/’
});

const context = await browser.newContext();
const page = await context.newPage();

await page.goto(‘https://example.com’);
})();

When to use this:

  • When you want to attach directly via WebSocket
  • Works across browsers exposing a debugger WebSocket endpoint
  • Handy for quick debugging or session reuse

Working with Existing Browser Contexts

Once Playwright connects to an already running browser, the next step is understanding how to work with its browser contexts. A context in Playwright acts like an isolated browser profile, holding cookies, storage, permissions, and session data.

When connecting to an existing browser, you can either reuse what’s already there or create fresh contexts without restarting the browser.

1. Listing and Inspecting Existing Contexts

When Playwright attaches to a live browser, it can detect:

  • Contexts created manually
  • Contexts created by earlier Playwright sessions
  • Tabs and pages already open in the browser
const contexts = browser.contexts();
console.log(‘Existing contexts:’, contexts.length);

This is useful when you want to inspect or reuse an environment that’s already active-like a logged-in session or a partially completed user flow.

2. Interacting with Existing Pages

You can access all open tabs inside each context:

const pages = contexts[0].pages();
console.log(‘Open tabs:’, pages.length);

await pages[0].bringToFront();
await pages[0].evaluate(() => console.log(‘Controlling an existing tab!’));

This is incredibly helpful when debugging, because you can:

  • Automate actions in a tab you manually opened
  • Check UI state that’s already present
  • Avoid re-navigating through the app from scratch

3. Creating a New Context (Recommended for Automation)

Even if you’re connected to a live browser, creating a new context is often cleaner:

const context = await browser.newContext();
const page = await context.newPage();

Why this is useful:

  • Prevents interference with manual tabs
  • Keeps automation clean and isolated
  • Avoids accidental clicks or navigation on existing pages

4. Reusing Authenticated Sessions

One of the biggest advantages of connecting to an existing browser is the ability to reuse logged-in sessions.

For example:

  • If you’re already logged into your app in Chrome
  • Playwright can reuse that exact profile/session
  • No need to run login steps every time
  • This dramatically speeds up debugging heavy authentication flows.

5. Mixing Manual + Automated Debugging

With this setup, you can:

  • Keep DevTools open
  • Inspect UI manually
  • Run Playwright commands on the same browser
  • Watch automation happen in real time

This hybrid workflow is why many testers call this their “fastest debugging setup” inside Playwright.

Common Use Cases

Connecting Playwright to an existing browser comes in handy across several real-world testing and debugging scenarios:

  • Faster debugging: No need to relaunch the browser or rebuild state every time-attach and continue where you left off.
  • Reusing logged-in sessions: Skip long or complex authentication steps by leveraging an already authenticated browser.
  • Working with open tabs: Automate on tabs you’ve manually opened, perfect for deep-in-flow debugging.
  • Live state inspection: Keep DevTools open and watch Playwright interact with the app in real time to catch UI or timing issues.
  • Quicker test iteration: Reduce development cycle time by avoiding repeated setup, navigation, and environment resets.

Best Practices for Connecting Playwright to an Existing Browser

To get the most out of connecting Playwright to an existing browser, keep these guidelines in mind:

  • Use separate contexts for automation: Create a new context even when connected to a live browser to avoid interfering with your manual tabs or active work.
  • Avoid running full test suites this way: Connecting to an existing browser is great for debugging, but not ideal for CI or full regression runs-use clean launches or cloud platforms instead.
  • Close contexts, not the browser: When done testing, close only the automation-created context. This prevents Playwright from shutting down your manually opened browser.
  • Keep the debugging port secure: Exposing a remote debugging port is powerful but risky-avoid using it on shared networks or production machines.
  • Use this workflow only for development: Reusing sessions, cookies, and open tabs is fantastic for debugging, but inconsistent for automated test reliability.
  • Leverage DevTools while connected: Keep DevTools open to inspect DOM, performance, or network behavior in real time as Playwright executes actions.

By now, you’ve seen how connecting Playwright to an existing browser can dramatically speed up local debugging—but it’s still a workflow best suited for development, not full test execution. For reliable, scalable, and cross-browser Playwright runs, BrowserStack Automate provides the controlled environments and tooling needed for production-grade testing.

Boost Your Playwright Automation with BrowserStack Automate

Connecting Playwright to an existing browser is great for local debugging-but it doesn’t solve the bigger challenges of scaling tests, ensuring cross-browser stability, or running on real user conditions. That’s where BrowserStack Automate truly elevates your workflow.

Primary benefits include:

  • Cross-browser and cross-platform coverage: Run Playwright tests on a wide range of browser and operating system combinations without maintaining local environments.
  • Zero infrastructure overhead: Execute tests instantly on cloud-based browsers, eliminating the need to install, update, or manage browsers and OS versions.
  • Comprehensive debugging insights: Access video recordings, console logs, network traces, and detailed session reports to diagnose failures efficiently.
  • Seamless configuration: Define browser capabilities using familiar Playwright configuration options, ensuring portability and consistency across environments.
  • CI/CD compatibility: Integrate tests easily with major CI/CD platforms to automate quality checks as part of your deployment pipeline.
  • Parallel execution: Run multiple Playwright tests simultaneously to significantly reduce overall test execution time.

Talk to an Expert

Conclusion

Connecting Playwright to an existing browser is one of those underrated techniques that can dramatically speed up your local debugging workflow. It allows you to reuse active sessions, work with already open tabs, and iterate much faster without constantly relaunching the browser. For development and troubleshooting, this approach can save hours and make your debugging loop far more efficient.

But while local connections are perfect for quick fixes and exploratory debugging, they aren’t built for large-scale, cross-browser automation. As soon as you need reliable environments, real devices, parallel execution, or seamless CI integration, you need a platform designed for production-grade testing. This is where BrowserStack Automate shines-offering real browsers, isolated environments, deep debugging insights, and instant scalability without any infrastructure overhead.

Try BrowserStack Now

Useful Resources for Playwright

Tool Comparisons:

Tags
Automation Testing Real Device Cloud Website Testing

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord