User Agents

Web browsers and everyday web tech, explained

Connect Playwright to an Existing Browser Session

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Connecting Playwright to an already-open browser session lets you take over a browser that was launched manually or by another tool, so you can reuse its login state, cookies, or open tabs without starting a fresh instance. This is especially useful for debugging, for automating steps after a manual login, or for integrating with a browser that a user has already configured. To follow this guide, you need a basic understanding of Playwright and Node.js (or Python), and you must have Playwright installed in your project.

What You'll Need

  • A Playwright project set up (Node.js or Python).
  • The browser you want to connect to (Chrome, Edge, or Chromium) installed.
  • For Chrome/Edge: the browser must be launched with a remote debugging port (see Step 1).
  • For Firefox or WebKit: you need to use a custom user data directory and launch the browser with Playwright's launchPersistentContext (see the FAQ).

Step-by-Step

  1. Close all instances of the browser you want to connect to. This ensures you start with a clean slate and avoid conflicts.
  2. Launch the browser with a remote debugging port. For Chrome or Edge, open a terminal and run the executable with the --remote-debugging-port=9222 flag. For example, on Windows: "C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222. On macOS: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --remote-debugging-port=9222. On Linux: google-chrome --remote-debugging-port=9222. Use a different port if 9222 is already in use.
  3. Optionally, use a separate user data directory. To avoid interfering with your regular browser profile, add --user-data-dir=/tmp/playwright-chrome (or any path) to the command. This is recommended for testing.
  4. Verify the debugging endpoint is accessible. Open a browser and go to http://localhost:9222/json/version. You should see a JSON response with browser and webSocketDebuggerUrl information. If you get an error, the port may be blocked or the browser didn't start correctly.
  5. In your Playwright script, connect to the browser using connectOverCDP. This method works for Chromium-based browsers. Here's a Node.js example:
    const { chromium } = require('playwright');
    (async () => {
      const browser = await chromium.connectOverCDP('http://localhost:9222');
      const defaultContext = browser.contexts()[0];
      const page = defaultContext.pages()[0];
      console.log(await page.title());
      // Now you can interact with the existing page or create new pages.
      await browser.close(); // This will not close the browser, only the connection.
    })();
  6. For Python, use the same method. Here's a Python example:
    from playwright.sync_api import sync_playwright
    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp("http://localhost:9222")
        default_context = browser.contexts[0]
        page = default_context.pages[0]
        print(page.title())
        browser.close()
  7. Interact with the existing pages. Once connected, you can access all open tabs via browser.contexts() and context.pages(). You can also create new pages in the same context, which will share cookies and localStorage.
  8. When done, close the connection. Calling browser.close() on the connected browser object only disconnects Playwright from the browser; it does not close the browser window itself. To close the browser, you must do it manually or via a script that sends a command to the debugging endpoint.

Common Mistakes

  • Forgetting the remote debugging port. Without it, the browser won't expose the debugging endpoint, and Playwright can't connect.
  • Using chromium.launch() instead of connectOverCDP. This creates a new browser instance instead of connecting to an existing one.
  • Assuming browser.close() closes the browser. It only closes the connection, leaving the browser open.
  • Not using a separate user data directory when needed. This can cause conflicts with your default profile, especially if you have extensions or multiple profiles.
  • Connecting to a browser that is already connected. Only one client can connect to a debugging port at a time. If you have another Playwright script connected, you'll get an error.

Tips

  • Use a high port number like 9222 or 9223 to avoid conflicts with common services.
  • Check the /json/version endpoint to confirm the browser is ready before running your script.
  • If you need to automate a login flow, connect to a browser where you've already logged in manually, then save the storage state for future use.
  • For Firefox or WebKit, you cannot use connectOverCDP because they don't support CDP. Instead, use launchPersistentContext with a user data directory to simulate an existing session.
  • Use --headless=new if you need a headless browser with debugging. Some versions of Chrome support this flag.

Troubleshooting

I get "Cannot connect to the target" or ECONNREFUSED. Ensure the browser is running with the correct port and that the port is not blocked by a firewall. Try curl http://localhost:9222/json/version to test.

The browser opens but Playwright can't find any pages. If you open a new tab after launching, it may be a blank page. Use browser.contexts() to see all contexts; sometimes the default context has no pages. Create a new page if needed.

I get "Target page, context or browser has been closed" This happens if the browser window is closed manually. Re-launch the browser with the debugging port and reconnect.

Multiple Playwright connections fail. Only one connection is allowed per debugging port. Close other scripts or use a different port.

Chrome doesn't allow remote debugging on some systems. On macOS, you may need to run the command with --user-data-dir to avoid issues with the default profile.

Frequently Asked Questions

Can I connect to a browser that was launched without the debugging port?

No. The browser must be started with --remote-debugging-port to expose the debugging interface.

Does connecting to an existing session share cookies and localStorage?

Yes, because you are connecting to the same browser context. Any cookies or storage in that context are accessible.

Can I use this with Firefox or Safari?

Playwright supports connecting to Firefox and WebKit using a different approach: launch a persistent context with a user data directory. There is no CDP support for these browsers, so connectOverCDP only works with Chromium-based browsers.

Will the browser close when I call browser.close()?

No. In Playwright, browser.close() on a connected browser only disconnects the client. The browser remains open.

Can I connect to a browser running on a different machine?

Yes, if the debugging port is accessible over the network. Use the machine's IP address instead of localhost, and ensure the port is open in the firewall.

How do I save the login state after connecting?

You can use context.storageState() to save cookies and localStorage, then reuse it in future scripts with launchPersistentContext.