User Agents

Web browsers and everyday web tech, explained

Fix Slow Headless Chrome and Failed File Downloads

· 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

To fix slow performance and failed downloads in headless Chrome, you must optimize the browser's launch arguments to reduce resource overhead and explicitly configure the Chrome DevTools Protocol (CDP) to enable download behavior, which is disabled by default in headless mode. By disabling unnecessary features like GPU acceleration and sandboxing (where appropriate) and using the Page.setDownloadBehavior command, you can stabilize your automation scripts and increase execution speed.

What You'll Need

  • A programming environment with Node.js or Python installed.
  • A browser automation library such as Puppeteer, Playwright, or Selenium.
  • The Chrome or Chromium binary compatible with your library version.
  • Administrative permissions to create folders for download paths on your local machine.

Step-by-Step

  1. Optimize Launch Arguments for Speed: Headless Chrome often struggles with memory leaks and unnecessary rendering processes. Add the following flags to your browser launch configuration to reduce the load:
    • --disable-gpu: Disables hardware acceleration, which is often unstable or unavailable in headless environments.
    • --no-sandbox: Bypasses the OS security layer; use this only in trusted environments (like Docker) to prevent crashes.
    • --disable-dev-shm-usage: Forces Chrome to use /tmp instead of /dev/shm, preventing crashes in containers with limited shared memory.
    • --disable-setuid-sandbox: Further reduces permission-related overhead.
    • --blink-settings=imagesEnabled=false: If you do not need to verify images, disabling them significantly speeds up page load times.
  2. Configure the Download Directory: Chrome cannot prompt a user for a save location in headless mode. You must define a specific path where files will be saved automatically. In Puppeteer or Playwright, ensure you have a valid absolute path to a folder on your system.
  3. Enable Downloads via Chrome DevTools Protocol (CDP): By default, headless Chrome blocks downloads for security. You must send a command to the browser to allow them. If using Puppeteer, use the following logic:
    const client = await page._client;
    await client.send('Page.setDownloadBehavior', { 
      behavior: 'allow', 
      downloadPath: '/your/absolute/path/to/downloads' 
    });
    This tells the browser to bypass the "Save As" dialog and write the file directly to the specified directory.
  4. Manage Memory and Zombie Processes: Slowdowns often occur because previous browser instances were not closed correctly. Always wrap your code in a try...finally block to ensure browser.close() is called regardless of whether the script succeeded or failed.
  5. Implement Smart Waiting: Avoid using fixed timers (e.g., sleep(5000)), which slow down your workflow. Instead, use waitForSelector or waitForNavigation. This ensures the script moves to the next step the millisecond the element is available.
  6. Handle File Completion: Since downloads happen asynchronously in the background, the script may finish before the file is fully written to disk. Implement a polling loop that checks the download folder for the existence of the file and ensures it does not end in .crdownload (the temporary Chrome extension) before proceeding.

Common Mistakes

  • Using Relative Paths: Providing a relative path for the download directory often leads to files being saved in the root of the system or failing entirely. Always use absolute paths.
  • Forgetting to Close the Browser: Leaving browser instances open consumes RAM and CPU, eventually slowing the entire system to a crawl.
  • Over-reliance on --no-sandbox: While it solves many crashes, it removes a layer of security. Do not use this when navigating to untrusted or third-party websites.
  • Ignoring Headless Mode Versions: Switching between headless: true (the old mode) and headless: 'new' (the updated Chrome headless mode) can change how downloads are handled. Ensure you are using the most current version of your library.

Tips

  • Use a Custom User Agent: Some websites detect the "HeadlessChrome" string in the User-Agent and serve a slower, simplified version of the page or block the request entirely. Set a real browser User-Agent string to avoid this.
  • Block Unnecessary Requests: Use request interception to block CSS, fonts, and analytics scripts. This reduces bandwidth and speeds up the DOMContentLoaded event.
  • Increase Memory Limits: If running in a Docker container, increase the shm-size to 2GB to prevent the browser from crashing on heavy pages.

Troubleshooting

If downloads are still failing after applying the CDP settings, check the following:

  • Permission Denied: Ensure the user running the script has write permissions for the downloadPath.
  • Incorrect CDP Version: If you updated Chrome but not your automation library, the Page.setDownloadBehavior command may be rejected. Update your packages to the latest stable version.
  • Network Timeouts: If the browser is slow to respond, increase the default timeout from 30 seconds to 60 seconds using page.setDefaultTimeout(60000).
  • Disk Space: Verify that the drive where the downloads are being saved is not full, as headless Chrome will fail silently without a disk-full error in the console.

Frequently Asked Questions

Why does Chrome block downloads in headless mode?

For security reasons, headless Chrome is designed to prevent automated scripts from writing files to a user's hard drive without explicit permission, which is why the CDP command is required.

Does disabling the GPU actually make it faster?

Yes, in headless environments (especially Linux servers), Chrome may attempt to find a GPU that doesn't exist, leading to timeouts and lag. Disabling it streamlines the rendering process.

How do I know when a download is actually finished?

The most reliable method is to monitor the target folder for the file and wait until the .crdownload temporary extension disappears.

Can I use headless Chrome to download PDFs?

Yes, but you may need to set the plugins.always_open_pdf_externally preference to true in the browser's user profile settings to prevent Chrome from trying to open the PDF in a built-in viewer.

Will --no-sandbox cause security risks?

Yes, it disables the primary security boundary between the browser process and the operating system. It should only be used in isolated environments like Docker containers.