Using Playwright CDP for Real-Device Testing
Playwright CDP connects to an existing Chromium browser; Android device automation uses a separate experimental API. Learn which path fits and how to set each up.
chromium.connectOverCDP() attaches Playwright to an already running Chromium-based browser through a Chrome DevTools Protocol (CDP) HTTP or WebSocket endpoint. That can be useful for inspecting or automating an existing desktop browser session, but it does not by itself connect Playwright to Chrome on an Android phone.
For Android hardware automation, Playwright provides a separate experimental Android API that uses ADB and targets Chrome for Android or Android WebView. For simulated mobile behavior, use device emulation; emulation changes browser settings but does not exercise physical hardware. See the official BrowserType API, Android API, and Emulation guide.
Choose the right Playwright connection
| Approach | What it targets | Use it when | Key limitation |
|---|---|---|---|
connectOverCDP() |
An existing Chromium-based browser exposed through a CDP endpoint | You need to attach to an already running browser and work with its contexts or pages | Playwright documents this as significantly lower fidelity than its Playwright protocol connection |
browserType.connect() |
A browser server exposed through Playwright’s protocol | You control both ends and need the Playwright protocol’s fuller functionality | It is a different connection setup; it is not a way to attach to an arbitrary phone browser |
| Playwright Android API | Chrome for Android or Android WebView on a device or Android Virtual Device (AVD) | You need Android-specific browser automation on hardware or an AVD | Experimental API with documented setup requirements and limitations |
| Device emulation | A browser configured with selected mobile parameters | You want to simulate viewport, user agent, screen dimensions, or touch behavior | It does not test actual device hardware |
These paths answer related but different questions. Use CDP for an existing Chromium browser endpoint. Use the Android API for Android Chrome or WebView. Use emulation when a simulated mobile configuration is sufficient.
Attach to an existing Chromium browser with CDP
The browser must already be running and expose a CDP endpoint reachable from the Playwright process. The API accepts an HTTP endpoint, such as http://localhost:9222, or a CDP WebSocket URL. Once connected, inspect the browser’s contexts and pages to find the existing target.
Example with Playwright for Node.js
Install Playwright in your project with npm install playwright. Start or configure a Chromium browser separately so it exposes a CDP endpoint, then run this script with that endpoint available.
const { chromium } = require('playwright');
(async () => {
const endpointURL = process.env.CDP_ENDPOINT || 'http://localhost:9222';
const browser = await chromium.connectOverCDP(endpointURL);
try {
const contexts = browser.contexts();
if (contexts.length === 0) {
throw new Error('The connected browser has no available default context.');
}
const context = contexts[0];
const pages = context.pages();
const page = pages[0];
if (!page) {
throw new Error('The connected context has no open pages.');
}
console.log('Connected page:', page.url());
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
console.log('Title:', await page.title());
} finally {
// Disconnect Playwright from the browser. This does not ask you to close
// the browser process that provided the CDP endpoint.
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Set CDP_ENDPOINT to the endpoint URL your browser environment provides. For example, a local endpoint might be http://localhost:9222. Do not assume that port is enabled or reachable by default; the browser must be launched or configured to expose it.
Connection checklist
- Start the Chromium-based browser with CDP enabled, or obtain a CDP endpoint from the browser environment you are using.
- Confirm the Playwright process can reach the endpoint. A URL that resolves only inside a different container or host will not work from your process.
- Call
chromium.connectOverCDP(endpointURL). - Inspect
browser.contexts(), then the relevant context’spages(). - Perform the required navigation or interaction and handle connection errors and timeouts.
- Disconnect when finished. If you need advanced Playwright functionality, consider the Playwright protocol connection described by
browserType.connect().
Automate a real Android device with Playwright’s Android API
Attaching to desktop Chrome over CDP is not the Android automation workflow. Playwright’s Android API is experimental and supports Chrome for Android and Android WebView. The documented setup requires an Android device or AVD emulator, authenticated ADB, Chrome 87 or newer, and the documented Chrome flag setting. Follow the current Android API documentation for the exact setup and flag instructions.
Node.js example using the Android API
This example discovers devices, selects one, launches Chrome, navigates, and captures a screenshot. It assumes the documented prerequisites are already satisfied and a device is available to ADB.
const { _android: android } = require('playwright');
(async () => {
const devices = await android.devices();
if (devices.length === 0) {
throw new Error('No Android device found. Check ADB authentication and device setup.');
}
const device = devices[0];
console.log('Android device:', device.model());
const context = await device.launchBrowser();
try {
const page = await context.newPage();
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
console.log('Title:', await page.title());
await page.screenshot({ path: 'android-page.png' });
} finally {
await context.close();
await device.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Playwright’s Android documentation notes that the device must be awake for screenshots, raw USB operation is not supported, and not all tests were run against the device. Treat this as experimental support and check the official documentation for current compatibility details before building a required test workflow around it.
When device emulation is enough
Playwright emulation configures browser parameters such as user agent, screen dimensions, viewport, and touch behavior. It is appropriate for checking responsive layouts or code paths that respond to those browser settings. It is not a substitute for testing sensors, hardware behavior, a particular Android build, or other characteristics of an actual phone.
const { chromium, devices } = require('playwright');
(async () => {
const browser = await chromium.launch();
try {
const context = await browser.newContext({
...devices['Pixel 5'],
});
const page = await context.newPage();
await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
console.log('Emulated viewport:', page.viewportSize());
} finally {
await browser.close();
}
})().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Device preset names and supported emulation settings are described in the Playwright emulation guide. Choose a preset or set the browser parameters your test needs; report results as emulated behavior rather than physical-device coverage.
Reliability and performance considerations
- CDP endpoint availability: The browser process must remain running and the endpoint must remain reachable. A browser restart or endpoint change requires reconnecting.
- Existing session state: CDP exposes the connected browser’s contexts and pages. Select the intended page rather than assuming the first page is always the one your test needs.
- Feature fidelity: Playwright explicitly warns that CDP has lower fidelity than the Playwright protocol connection. If an operation behaves differently or is unavailable, check whether the connection mode is the cause.
- Android readiness: ADB authentication, Chrome version, the documented Chrome flag, and an awake device affect whether Android automation can proceed. AVDs are an option where physical hardware is not required.
- Test coverage: Emulation gives repeatable browser settings but does not establish that a physical phone behaves identically. Android API support is experimental, and the documentation says not all tests were run against the device.
- Timeouts: Set navigation and operation timeouts to match the page and environment. A slow page, sleeping device, or disconnected endpoint can look like a test failure unless the error is recorded with the target URL and connection path.
Troubleshooting
| Symptom | Likely cause | What to check or change |
|---|---|---|
| CDP connection is refused or times out | The browser is not exposing CDP, the endpoint is wrong, or the process cannot reach that host and port | Verify the browser launch/configuration and endpoint, then check network reachability from the Playwright process. Use the actual endpoint supplied by the environment. |
| Connected browser has no pages | The context has no open page, or the script selected the wrong context | Inspect every entry in browser.contexts() and each context’s pages(). Create a page in the appropriate context if that is suitable for the workflow. |
| A CDP workflow lacks expected functionality | CDP connection fidelity differs from Playwright’s protocol connection | Check the BrowserType API guidance and use browserType.connect() when you control a compatible Playwright browser server and need that protocol. |
| No Android devices are discovered | ADB is unavailable, the device is not authorized, or the Android setup is incomplete | Confirm ADB authentication and follow the Android API’s documented setup for the device or AVD. |
| Android Chrome does not launch or attach | The Chrome version or required flag setting may not meet the documented prerequisites | Check that Chrome is version 87 or newer and follow the current Chrome flag instructions in the Android API documentation. |
| Android screenshot is missing or fails | The device may be asleep | Wake the device before taking a screenshot, as required by the documented limitation. |
| Expectations for USB-only operation fail | Raw USB operation is not supported by Playwright’s Android API | Use the supported ADB setup described in the official documentation; do not assume direct raw USB access is available through this API. |
| A test passes in emulation but fails on a phone | Emulation does not reproduce every hardware or operating-system condition | Run the test using the Android API on a physical device or AVD when Android browser behavior is the target, and record which target was used. |
Or skip the browser setup
If the task is to capture a website as an image or PDF rather than interact with a live browser session, ScreenshotNeo offers a website screenshot API and MCP server. A single GET request can return a PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
require('fs').writeFileSync('shot.webp', image);
- Cookie banners, newsletter popups, and chat widgets are removed before the shot; each cleanup step can be turned off.
- Bot checks, blank pages, failed loads, timeouts, and cache hits are never billed. Responses include
X-Page-VerdictandX-Billedheaders. - An MCP server lets AI agents use
take_screenshot,get_page_info, andcapture_pdf. - The free plan includes 1,000 screenshots a month with no card. Paid plans start at $5 for 3,000 screenshots.
Sign up for ScreenshotNeo and get 1,000 free screenshots a month with no card.
Frequently asked questions
Can connectOverCDP() connect to Chrome on my phone?
Do not treat the desktop Chromium CDP workflow as Android device support. Use Playwright’s separate Android API for documented Android Chrome and WebView automation.
Does an Android Virtual Device count as real-device testing?
An AVD runs an Android environment but is an emulator. Distinguish it from testing on physical hardware when reporting coverage.
Should I use CDP or browserType.connect()?
Use CDP when you need to attach to an existing Chromium browser endpoint. The Playwright documentation points to browserType.connect() for the higher-fidelity Playwright protocol connection.
Does a screenshot API replace Playwright tests?
No. A screenshot API captures a rendered page; Playwright is the relevant choice when a workflow needs browser automation, interaction, or device-specific test behavior.


