🔥 Playwright Pro-Tip: Struggling to simulate realistic network latency or device sensors in your Playwright tests? Most engineers overlook this browser superpower.
📌 Problem Statement
High-fidelity testing often demands advanced browser condition simulations beyond standard Playwright APIs. Think network throttling, geolocation spoofing, or device sensor emulation. Without direct access, these scenarios are hard to reproduce, leading to missed bugs.
💡 Solution & Code Walkthrough
Playwright offers a CDPSession object to tap directly into the Chrome DevTools Protocol (CDP). This allows granular control over browser internals, enabling powerful simulations like network throttling.
✅ Obtain a CDPSession from a BrowserContext or Page instance.
✅ Use client.send('Domain.command', {params}) to execute CDP commands.
✅ Listen for CDP events to react to browser changes.
import { test, Page } from '@playwright/test';
test('simulate network throttling via CDP', async ({ page }) => {
const client = await page.context().newCDPSession(page);
await client.send('Network.enable');
await client.send('Network.emulateNetworkConditions', {
offline: false,
latency: 2000, // 2000ms delay
downloadThroughput: 500 * 1024 / 8, // 500 KB/s (bytes/s)
uploadThroughput: 200 * 1024 / 8, // 200 KB/s (bytes/s)
});
console.log('Navigating with throttling...');
await page.goto('https://example.com');
await client.detach();
});
• This code snippet demonstrates throttling network conditions, making page.goto() experience a simulated slow connection. CDP domains like Emulation can also spoof geolocation or device sensors.
🔑 Key Takeaways
• CDP enables deep browser interaction beyond Playwright's high-level APIs.
• Use newCDPSession() on BrowserContext or Page.
• client.send() executes raw CDP commands (Domain.command).
• Essential for advanced performance, security, accessibility testing.
❌ Overuse can make tests brittle; use judiciously for specific conditions.
❓ Quick Summary Q&A
Q: What is CDPSession in Playwright?
A: An object for direct CDP access, enabling granular browser control.
Q: Why use CDP with Playwright?
A: To simulate network throttling, geolocation, or device sensors beyond standard Playwright APIs.
TAGS: playwright, cdp, network throttling, browser automation, testing, typescript, devtools protocol
────────────────────────────────────────
Level up your test automation skills!
────────────────────────────────────────
📲 𝐅𝐑𝐄𝐄 𝐌𝐎𝐁𝐈𝐋𝐄 𝐀𝐏𝐏 — 𝟔𝟎𝟎+ 𝐒𝐃𝐄𝐓 𝐐&𝐀𝐬
Practice real-world interview scenarios offline on the free QA Automation & SDET Prep app:
🤖 𝐆𝐨𝐨𝐠𝐥𝐞 𝐏𝐥𝐚𝐲 (𝐀𝐧𝐝𝐫𝐨𝐢𝐝):
https://play.google.com/store/apps/details?id=com.app.seleniuminterviewquestions&referrer=utm_source%3Ddevto%26utm_medium%3Darticle%26utm_campaign%3Dselenium_20261105
🍎 𝐀𝐩𝐩 𝐒𝐭𝐨𝐫𝐞 (𝐢𝐎𝐒):
https://apps.apple.com/app/id6786760948?pt=128640464&ct=devto_selenium_20261105&mt=8
────────────────────────────────────────
────────────────────────────────────────
Top comments (0)