What is Headless Mode?
Playwright can run browsers in headless mode, which executes browser automation without displaying the browser UI. This provides several advantages:
- Faster execution - No GUI rendering overhead
- Lower resource consumption - Reduced memory and CPU usage
- Server-friendly - Perfect for CI/CD pipelines and production environments
- Background processing - Ideal for automated tasks and web scraping
Default Behavior
Important: Playwright runs in headless mode by default. You only need to explicitly set headless: true
for clarity or when overriding previous configurations.
JavaScript Examples
Basic Headless Usage
const { chromium } = require('playwright');
(async () => {
// Headless by default
const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
const title = await page.title();
console.log(`Page title: ${title}`);
await browser.close();
})();
Explicit Headless Configuration
const { chromium, firefox, webkit } = require('playwright');
(async () => {
// Explicitly set headless mode
const browser = await chromium.launch({
headless: true,
args: ['--no-sandbox', '--disable-dev-shm-usage'] // Common headless args
});
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://example.com');
// Take screenshot in headless mode
await page.screenshot({ path: 'example.png' });
await browser.close();
})();
Toggling Between Headless and Headed
const { chromium } = require('playwright');
const runInHeadlessMode = process.env.NODE_ENV === 'production';
(async () => {
const browser = await chromium.launch({
headless: runInHeadlessMode,
slowMo: runInHeadlessMode ? 0 : 100 // Slow down in headed mode for debugging
});
const page = await browser.newPage();
await page.goto('https://example.com');
await browser.close();
})();
Python Examples
Synchronous API
from playwright.sync_api import sync_playwright
def run_headless_scraper():
with sync_playwright() as p:
# Headless by default
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://example.com")
title = page.title()
print(f"Page title: {title}")
browser.close()
run_headless_scraper()
Asynchronous API
import asyncio
from playwright.async_api import async_playwright
async def run_headless_scraper():
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
page = await browser.new_page()
await page.goto("https://example.com")
# Extract data in headless mode
content = await page.content()
await page.screenshot(path="screenshot.png")
await browser.close()
asyncio.run(run_headless_scraper())
Environment-Based Configuration
import os
from playwright.sync_api import sync_playwright
def run_with_environment_config():
is_production = os.getenv('ENVIRONMENT') == 'production'
with sync_playwright() as p:
browser = p.chromium.launch(
headless=is_production,
args=['--no-sandbox'] if is_production else []
)
page = browser.new_page()
page.goto("https://example.com")
if not is_production:
# Only in development - show browser for debugging
page.pause() # Opens Playwright Inspector
browser.close()
run_with_environment_config()
All Browser Types
Headless mode works with all Playwright browsers:
const { chromium, firefox, webkit } = require('playwright');
// Chromium (Chrome/Edge)
const chromiumBrowser = await chromium.launch({ headless: true });
// Firefox
const firefoxBrowser = await firefox.launch({ headless: true });
// WebKit (Safari)
const webkitBrowser = await webkit.launch({ headless: true });
Common Use Cases for Headless Mode
- Web scraping - Extract data without visual interference
- Automated testing - Run tests in CI/CD pipelines
- PDF generation - Create PDFs from web pages
- Screenshot automation - Capture page screenshots programmatically
- Performance monitoring - Monitor website performance metrics
Debugging Headless Issues
When debugging headless automation, you can temporarily switch to headed mode:
// For debugging - switch to headed mode
const browser = await chromium.launch({
headless: false,
devtools: true // Opens DevTools automatically
});
This allows you to visually inspect what's happening during automation before switching back to headless mode for production.