Why Headless Chrome Runs Forever & How to Stop It
In this article
- What Headless Chrome Is and Why It Exists
- Why It Doesn’t Exit on Its Own
- How to Stop It: The Right Way
- Common Pitfalls and How to Avoid Them
- How to Choose Between Headless and Headful
- Comparison: Puppeteer vs. Playwright vs. Selenium
- Costs and Resource Usage
- Safety and Security Considerations
- Alternatives to Headless Chrome
- Frequently Asked Questions
Headless Chrome runs forever because the Node.js process that launched it keeps the event loop alive, waiting for the browser process to exit—which it never does on its own. To stop it, you must explicitly close the browser with browser.close() (or driver.quit() in Selenium) and, if needed, force-exit the Node process with process.exit().
What Headless Chrome Is and Why It Exists
Headless Chrome is the same Chrome browser you use daily, but without any visible window. It runs in the background, loading pages, executing JavaScript, and rendering content—all without a GUI. Developers use it for automated testing, web scraping, generating PDFs or screenshots, and server-side rendering of single-page apps.
The “headless” mode was introduced in Chrome 59 (2017) and later revamped in Chrome 112 (2023) with the new headless mode that uses the same code path as the regular browser. This means it behaves almost identically to a real user’s Chrome, which is both a blessing (accurate testing) and a curse (it can be resource-hungry and stubborn to terminate).
Why It Doesn’t Exit on Its Own
When you start headless Chrome from a script, it launches as a separate process. The script (often Node.js or Python) communicates with it via a protocol (Chrome DevTools Protocol or WebDriver). The browser process stays alive for two main reasons:
- Open pages and active timers: Even if your script finishes its task, the browser keeps running because the page’s JavaScript may have set timers, intervals, or network requests that haven’t completed.
- The event loop in your script: In Node.js, the
puppeteerorplaywrightlibrary keeps the event loop alive while the browser is connected. If you don’t close the browser, the script never reaches its end and never exits.
Think of it like leaving a car engine running after you’ve parked—the car doesn’t turn off just because you’ve stopped driving. You have to turn the key (or press the button) to shut it down.
How to Stop It: The Right Way
The cleanest way to stop headless Chrome is to close it programmatically. Here’s how in the most common tools:
- Puppeteer: Call
await browser.close()after your work is done. This closes all pages and the browser process. - Playwright: Use
await browser.close()(orcontext.close()if you only need to close a context). - Selenium WebDriver: Call
driver.quit()to close the browser and end the session. - Manual kill: If the process is stuck, you can kill it from the command line. On Linux/macOS:
pkill chromeorkill <PID>. On Windows:taskkill /F /IM chrome.exe.
If you’re using a script that runs periodically (like a cron job), ensure you wrap your code in a try/finally block so the browser always closes, even if an error occurs.
Common Pitfalls and How to Avoid Them
Even with browser.close(), you may still see lingering processes. Here are the usual culprits:
- Unhandled promises: If you forget to
awaitthe close call, the script may exit before the browser is fully shut down, leaving orphans. - Multiple browser instances: If you launch more than one browser (e.g., in a loop), you must close each one individually.
- Child processes from the browser: Chrome spawns sub-processes for each tab, GPU, etc. Closing the main browser should kill them, but if the main process is killed forcefully (e.g.,
SIGKILL), some children may survive. - Resource leaks: If you create many pages but never close them, memory usage climbs. Always close pages or contexts when done.
To diagnose, run ps aux | grep chrome (Linux/macOS) or check Task Manager (Windows) to see how many Chrome processes are running. If you see dozens, something in your code isn’t closing them properly.
How to Choose Between Headless and Headful
Sometimes the solution is not to use headless at all. Headful (regular) Chrome runs in a visible window and is easier to debug because you can see what’s happening. Headless is faster and uses fewer resources, but it can hide issues like layout shifts or pop-ups that only appear when the browser is visible.
For most automated testing, headless is the default choice because it’s lighter and can run on servers without a display. However, if you’re debugging a flaky test, run it headful temporarily to see what’s going on. Tools like Puppeteer and Playwright make it trivial to switch by changing a single option (headless: false).
Comparison: Puppeteer vs. Playwright vs. Selenium
Each tool has its own way of managing the browser lifecycle:
- Puppeteer: Chrome-only, lightweight, and easy to learn. It gives you low-level control but requires you to manage the browser lifecycle manually.
- Playwright: Supports Chromium, Firefox, and WebKit. It has a more robust auto-waiting system and better handling of browser contexts, which can reduce the chance of hanging processes.
- Selenium: The oldest and most widely supported, especially for cross-browser testing. It uses WebDriver protocol, which can be more verbose but works with any browser.
All three allow you to close the browser cleanly, but Playwright’s context-based model often makes it easier to isolate tests and ensure cleanup.
Costs and Resource Usage
Headless Chrome is not free in terms of system resources. Each instance can consume 100–300 MB of RAM, depending on the page complexity. If you run many instances in parallel (e.g., for load testing), memory can quickly become a bottleneck. On cloud servers, this translates to higher costs if you need to scale up.
To reduce resource usage:
- Use a single browser instance and open new pages in the same browser instead of launching a new browser for each task.
- Close pages you no longer need.
- Use
--disable-dev-shm-usageflag in Docker environments to avoid shared memory issues. - Limit the number of concurrent instances based on your server’s RAM.
Safety and Security Considerations
Running headless Chrome can introduce security risks if you’re not careful:
- Command injection: If you pass user input to the browser URL, sanitize it to prevent malicious code execution.
- Resource exhaustion: An attacker could trigger many headless instances, causing a denial-of-service. Implement rate limiting and timeouts.
- Data leakage: Headless Chrome can access internal network resources if the server is on a private network. Be cautious about what sites you allow it to visit.
Always run headless Chrome with the least privilege necessary. Use a dedicated user account, and avoid running it as root. In Docker, use a non-root user and consider using a read-only filesystem.
Alternatives to Headless Chrome
If headless Chrome is causing too many headaches, consider these alternatives:
- Puppeteer’s Firefox support: Not officially, but Playwright supports Firefox headless, which may behave differently.
- PhantomJS: An older headless browser, but it’s no longer maintained and lacks modern JavaScript support.
- HtmlUnit: A Java-based headless browser that’s lightweight but not great for modern web apps.
- Using a real browser with a virtual display: Tools like Xvfb let you run a full Chrome in a virtual framebuffer, which can be more stable for complex sites.
For simple scraping tasks, you might not need a full browser at all—use curl or a library like requests plus an HTML parser. But for JavaScript-heavy sites, a headless browser is often necessary.
Frequently Asked Questions
Why does my Puppeteer script hang even after browser.close()?
If you call browser.close() but your script still hangs, it’s likely because you have other open handles (like a server or a database connection) that keep the Node.js event loop alive. Use process.exit() to force exit after cleanup, or ensure all other resources are closed.
How do I kill all headless Chrome processes at once?
On Linux/macOS, run pkill -f "chrome-headless" or pkill chrome. On Windows, use taskkill /F /IM chrome.exe. Be careful—this will kill all Chrome instances, not just headless ones.
Is headless Chrome slower than regular Chrome?
It’s usually slightly faster because it doesn’t render to a screen, but the difference is often negligible. The main speed gain comes from not having to draw pixels, which can save a few milliseconds per page load.
Can I run headless Chrome without a display on a server?
Yes, that’s the primary use case. Headless Chrome runs fine on servers without a display, as long as you have the necessary system libraries installed (like libnss3, libatk, etc.).
Why does headless Chrome use so much CPU?
It’s often due to heavy JavaScript on the page, infinite animations, or a memory leak in your script. Try disabling images and CSS with page.setRequestInterception to reduce load, and ensure you’re not keeping the browser alive unnecessarily.
What is the difference between old and new headless mode?
The old headless mode (Chrome 59–111) used a separate implementation that didn’t support some features like extensions. The new headless mode (Chrome 112+) uses the same code as the regular browser, so it supports everything, including extensions and GPU acceleration.