Skip to content

Playwright integration ​

The flow is local API launch → read data.debuggingPort → connect over CDP → automate → stop through the API. The API requires active Pro and a running, signed-in client. Use the actual API address and api-key shown in the client.

1. Launch and read the port ​

http
POST http://127.0.0.1:{port}/api/launchBrowser
Content-Type: application/json
api-key: YOUR_API_KEY
json
{ "id": 1 }
json
{ "success": true, "data": { "debuggingPort": 9222 } }

The response example reflects the current client; Apifox leaves these response fields unspecified. Replace the service port and profile ID. Connect CDP to 9222 in this example, not to the API service port. See Launch a profile for name/remark selectors and tempLaunchArgs.

2. Python ​

Install requests and playwright with pip. The complete example includes HTTP checks, CDP port validation, and cleanup:

python
import requests
from playwright.sync_api import sync_playwright

BASE_URL = "http://127.0.0.1:9000"  # Replace with the client API address
PROFILE_ID = 1  # Replace with an existing profile ID
session = requests.Session()
session.headers.update({"api-key": "YOUR_API_KEY"})


def call_api(endpoint, body):
    response = session.post(
        f"{BASE_URL}{endpoint}", json=body, timeout=(5, 60)
    )
    response.raise_for_status()
    payload = response.json()
    if not isinstance(payload, dict) or payload.get("success") is not True:
        raise RuntimeError(payload)
    return payload


launch = call_api("/api/launchBrowser", {"id": PROFILE_ID})
try:
    port = launch.get("data", {}).get("debuggingPort")
    if not isinstance(port, int) or isinstance(port, bool) or not 0 < port < 65536:
        raise RuntimeError(f"Missing or invalid data.debuggingPort: {launch}")

    with sync_playwright() as p:
        browser = p.chromium.connect_over_cdp(f"http://127.0.0.1:{port}")
        if not browser.contexts:
            raise RuntimeError("No profile context returned by CDP")
        context = browser.contexts[0]
        page = context.new_page()
        page.goto("https://example.com", wait_until="domcontentloaded")
        print(page.title())
finally:
    try:
        print(call_api("/api/stopBrowser", {"id": PROFILE_ID}))
    finally:
        session.close()

3. Node.js ​

Requires Node.js 18+ and playwright. Save as a .mjs file and install dependencies with npm install playwright.

javascript
import { chromium } from 'playwright';

const BASE_URL = 'http://127.0.0.1:9000'; // Replace with the client API address
const PROFILE_ID = 1;
const headers = { 'Content-Type': 'application/json', 'api-key': 'YOUR_API_KEY' };

async function callApi(endpoint, body) {
  const response = await fetch(BASE_URL + endpoint, {
    method: 'POST',
    headers,
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(60_000),
  });
  const payload = await response.json();
  if (!response.ok || payload?.success !== true) {
    throw new Error(JSON.stringify(payload));
  }
  return payload;
}

const launch = await callApi('/api/launchBrowser', { id: PROFILE_ID });
try {
  const port = launch.data?.debuggingPort;
  if (!Number.isInteger(port) || port <= 0 || port >= 65536) {
    throw new Error('Missing or invalid data.debuggingPort');
  }
  const browser = await chromium.connectOverCDP('http://127.0.0.1:' + port);
  const context = browser.contexts()[0];
  if (!context) throw new Error('No profile context returned by CDP');
  const page = await context.newPage();
  await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
  console.log(await page.title());
} finally {
  await callApi('/api/stopBrowser', { id: PROFILE_ID });
}

Reuse the profile context

Use browser.contexts()[0] (Python: browser.contexts[0]). Do not call chromium.launch() or create a replacement browser context, or the script may no longer use the intended profile state.

4. Puppeteer ​

Install puppeteer-core and use the debuggingPort obtained above:

javascript
const puppeteer = require('puppeteer-core');

async function connectProfile(debuggingPort) {
  return puppeteer.connect({
    browserURL: `http://127.0.0.1:${debuggingPort}`,
  });
}

Stop the profile through /api/stopBrowser after automation; puppeteer.disconnect() only detaches the automation connection.

5. Troubleshooting ​

SymptomCheck
HTTP 401Copy the current api-key from the client
HTTP 403 / VIP capability errorVerify Pro, sign-in, and service connectivity
No debugging portRead data.debuggingPort, not a top-level field
Wrong profile stateAttach with CDP and reuse the existing profile context
Launch timeoutAllow at least 60 seconds; query the running list before retrying
success: falseRead the error and troubleshooting reference