User Agents

Web browsers and everyday web tech, explained

Puppeteer: How to Close Browser After Navigation Timeout

· 4 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 close a Puppeteer browser after a navigation timeout, you must wrap your navigation logic in a try-catch block and call browser.close() within the catch block. Because a timeout throws an error that halts the execution of your script, the browser process will remain open in the background (creating a "zombie" process) unless you explicitly instruct Puppeteer to shut it down when that error occurs.

What You'll Need

  • Node.js installed on your machine.
  • The puppeteer package installed via npm (npm install puppeteer).
  • A basic understanding of JavaScript asynchronous functions (async/await).

Step-by-Step

  1. Initialize the Browser: Start by launching your browser instance. Store the browser object in a variable that is accessible to both your main logic and your error handling block.
  2. Create a New Page: Open a new tab using browser.newPage(). This is where your navigation will take place.
  3. Set a Custom Timeout: By default, Puppeteer waits 30 seconds for navigation. If you need a shorter or longer window, use page.setDefaultNavigationTimeout(milliseconds) or pass a timeout option directly into the goto method.
  4. Implement the Try-Catch Block: Wrap the page.goto() call inside a try { ... } catch (error) { ... } block. This ensures that if the navigation fails to complete within the allotted time, the script doesn't simply crash, but instead moves to the recovery phase.
  5. Handle the Timeout Error: Inside the catch block, check if the error is a timeout. While you can log the specific error, the priority is to ensure the cleanup code is reached.
  6. Execute browser.close(): Call await browser.close() inside the catch block. This terminates the Chromium process and frees up system memory.
  7. Add a Final Cleanup: It is best practice to also place await browser.close() at the very end of your try block or in a finally block to ensure the browser closes regardless of whether the navigation succeeded or failed.

Common Mistakes

  • Closing the Page instead of the Browser: Calling page.close() only closes the tab. If you launched the browser using puppeteer.launch(), the main browser process will continue to run in the background, consuming RAM.
  • Forgetting the "await" Keyword: browser.close() is an asynchronous operation. If you omit await, the Node.js process might exit before the browser has actually finished shutting down, potentially leaving orphaned processes.
  • Placing the Close Call inside the Try Block Only: If the goto method times out, the code execution jumps immediately to the catch block. Any code following the failed navigation inside the try block is skipped.
  • Ignoring the Error Object: Not logging the error in the catch block makes it difficult to distinguish between a network timeout and a different type of crash (like a target closed error).

Tips

  • Use the Finally Block: Instead of putting browser.close() in both the try and catch blocks, use a finally { await browser.close(); } block. This guarantees the browser closes no matter what happens.
  • Wait Until Network Idle: To prevent timeouts on heavy pages, use waitUntil: 'networkidle2' in your goto options. This tells Puppeteer to wait until there are no more than two active network connections.
  • Headless Mode: When debugging timeout issues, set headless: false in your launch options. This allows you to see if the page is actually hanging or if it is just taking longer than your timeout setting.
  • Memory Monitoring: If you are running a loop of many pages, monitor your system's memory. Even with browser.close(), repeated crashes can sometimes lead to memory leaks if not handled cleanly.

Troubleshooting

If you find that the browser is still running in your Task Manager or Activity Monitor after the script finishes, check the following:

  • Unhandled Promise Rejections: Ensure you aren't missing an await somewhere in your chain. An unhandled promise can prevent the script from reaching the close() command.
  • Zombie Processes: If a script crashes violently (e.g., a segmentation fault), the catch block may never execute. In these cases, you may need to manually kill the processes using a command like pkill chrome or taskkill /f /im chrome.exe.
  • Timeout Value Too Low: If you are seeing constant timeouts, check your internet connection or increase the timeout value. A 5-second timeout is often too aggressive for modern, script-heavy websites.
  • Incorrect Scope: Ensure the browser variable is defined in a scope where the catch block can see it. If you define const browser inside the try block, it will be unavailable in the catch block.

Frequently Asked Questions

Does page.close() stop the browser process?

No, page.close() only closes the specific tab or page. To stop the entire browser and all its associated processes, you must use browser.close().

What is the default navigation timeout in Puppeteer?

The default timeout is 30 seconds. If the page does not load within this window, Puppeteer throws a TimeoutError.

Can I set the timeout to never expire?

Yes, you can set the timeout to 0 using page.setDefaultNavigationTimeout(0), which disables the timeout entirely. However, this is risky as it can lead to scripts hanging indefinitely.

Why does my script crash before it hits the catch block?

This usually happens if there is a syntax error or if an error occurs outside of the try-catch wrapper. Ensure all asynchronous calls are properly awaited and wrapped.

What is the difference between networkidle0 and networkidle2?

networkidle0 waits until there are zero active network connections for at least 500ms. networkidle2 waits until there are no more than two active connections, which is better for pages with long-polling requests.