User Agents

Web browsers and everyday web tech, explained

Debug Playwright Headless Browsers: A Complete Guide

· 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

Debugging a headless browser in Playwright requires transitioning from a "black box" execution environment to one where you can observe the DOM, network traffic, and execution flow in real-time. Because headless mode suppresses the graphical user interface, errors often manifest as generic timeouts or failed assertions without visual context. By utilizing headed mode, the Playwright Inspector, and trace viewers, you can pinpoint exactly where a script fails and why.

What You'll Need

  • Node.js installed on your local machine.
  • A project with Playwright initialized (npm init playwright@latest).
  • A code editor (Visual Studio Code is recommended for its native Playwright extension).
  • A target website or local development server to test against.

Step-by-Step

  1. Switch to Headed Mode: The fastest way to see what is happening is to disable headless mode. In your playwright.config.ts or playwright.config.js file, locate the use object and set headless: false. Alternatively, if running via command line, use npx playwright test --headed. This allows you to watch the browser interact with the page in real-time.
  2. Use the Playwright Inspector: Launch the Playwright Inspector to step through your test line-by-line. Run your tests with the PWDEBUG=1 environment variable: PWDEBUG=1 npx playwright test. This opens a separate window that allows you to pause execution, resume, and explore the page using the "Explore" tool to generate selectors automatically.
  3. Implement SlowMo: When running in headed mode, the browser often moves faster than the human eye can follow. Add slowMo: 100 (milliseconds) to your browser launch options in the config file. This introduces a deliberate delay between every action, making it easier to spot where a click misses its target or a popup appears unexpectedly.
  4. Enable Tracing: Traces are the most powerful debugging tool for headless environments (like CI/CD). In your config, set trace: 'on-first-retry' or trace: 'retain-on-failure'. After a test fails, Playwright saves a zip file containing a full recording of the test. Open this using npx playwright show-trace path/to/trace.zip to view a timeline, snapshots of the DOM at every step, and network logs.
  5. Capture Screenshots and Videos: For intermittent failures, configure the project to save visual evidence. Set screenshot: 'only-on-failure' and video: 'retain-on-failure' in the configuration. This provides a static image or a movie of the failure, which is essential for identifying layout shifts or unexpected modal overlays.
  6. Inspect Console Logs: Headless browsers still produce console logs that are hidden from you. Listen for the console event on the page object to pipe browser logs into your terminal: page.on('console', msg => console.log(`Browser Log: ${msg.text()}`));. This reveals JavaScript errors occurring within the page itself.
  7. Monitor Network Traffic: If a test fails because data isn't loading, use the page.on('requestfailed') and page.on('response') listeners. This helps you determine if an API call returned a 404 or 500 error, which would explain why an element never appeared on the screen.

Common Mistakes

  • Over-reliance on Hard Sleeps: Using page.waitForTimeout(5000) is a common mistake. This leads to flaky tests and slow execution. Instead, use web-first assertions like expect(locator).toBeVisible() which automatically poll the page.
  • Ignoring the Difference Between Headed and Headless: Some websites detect headless browsers and serve different content or trigger CAPTCHAs. If a test passes in headed mode but fails in headless, check your User-Agent string or viewport settings.
  • Using Absolute XPaths: Relying on long, absolute paths (e.g., /html/body/div[1]/div[2]/span) makes tests brittle. If the UI changes slightly, the test breaks. Use Playwright's built-in locators like getByRole or getByText.
  • Forgetting to Close the Browser: In custom scripts, failing to call browser.close() can leave zombie browser processes running in the background, consuming system memory.

Tips

  • Use the VS Code Extension: Install the official Playwright extension to run tests by clicking a "Play" button next to the code and to use the "Pick Locator" tool directly in the editor.
  • Leverage the Console: While paused in the Playwright Inspector, you can use the browser's own DevTools (F12) to test CSS selectors or execute JavaScript commands against the live page.
  • Test Across Viewports: Ensure your debugging includes different screen sizes. A button that is visible on a desktop may be hidden behind a hamburger menu on a mobile viewport, causing headless failures.
  • Isolate the Failure: Use test.only() to run only the failing test case. This reduces noise in the logs and speeds up the iteration cycle during debugging.

Troubleshooting

If the browser is not launching or the Inspector is not appearing, first verify that your browser binaries are up to date by running npx playwright install. If you are debugging in a Docker container or a remote Linux server, you cannot use headed mode unless you have an X11 server or a VNC setup; in these cases, rely exclusively on Tracing and Screenshots.

When facing "Timeout Exceeded" errors, check if the element is inside an iframe. Playwright requires you to target the frame specifically using page.frameLocator(). If the element exists but is not "interactable," check for overlapping elements like transparent overlays or loading spinners that might be blocking the click.

Frequently Asked Questions

Why does my test pass in headed mode but fail in headless?

This is often due to differences in default viewport sizes, timing issues where the headless browser renders faster than the assets load, or the website detecting and blocking headless browser signatures.

How do I see the network requests in a headless run?

The best way is to use the Playwright Trace Viewer. It provides a full network tab similar to Chrome DevTools, showing every request and response that occurred during the test.

Can I debug a test that is running in a CI/CD pipeline?

Yes, by enabling trace: 'retain-on-failure'. You can then download the trace artifact from your CI provider and open it locally using the show-trace command.

What is the difference between the Inspector and the Trace Viewer?

The Inspector is for live, interactive debugging while the test is running. The Trace Viewer is for post-mortem analysis of a test that has already completed.

How do I handle pop-ups that only appear occasionally?

Use page.waitForSelector() with a short timeout inside a try-catch block, or use a listener for page.on('dialog') to handle alerts and confirms automatically.