Puppeteer: How to Close Browser After Navigation Timeout
In this article
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
puppeteerpackage installed via npm (npm install puppeteer). - A basic understanding of JavaScript asynchronous functions (async/await).
Step-by-Step
- 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.
- Create a New Page: Open a new tab using
browser.newPage(). This is where your navigation will take place. - 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 thegotomethod. - Implement the Try-Catch Block: Wrap the
page.goto()call inside atry { ... } 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. - Handle the Timeout Error: Inside the
catchblock, check if the error is a timeout. While you can log the specific error, the priority is to ensure the cleanup code is reached. - Execute browser.close(): Call
await browser.close()inside thecatchblock. This terminates the Chromium process and frees up system memory. - Add a Final Cleanup: It is best practice to also place
await browser.close()at the very end of yourtryblock or in afinallyblock 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 usingpuppeteer.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 omitawait, 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
gotomethod times out, the code execution jumps immediately to thecatchblock. Any code following the failed navigation inside thetryblock is skipped. - Ignoring the Error Object: Not logging the error in the
catchblock 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 thetryandcatchblocks, use afinally { 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 yourgotooptions. This tells Puppeteer to wait until there are no more than two active network connections. - Headless Mode: When debugging timeout issues, set
headless: falsein 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
awaitsomewhere in your chain. An unhandled promise can prevent the script from reaching theclose()command. - Zombie Processes: If a script crashes violently (e.g., a segmentation fault), the
catchblock may never execute. In these cases, you may need to manually kill the processes using a command likepkill chromeortaskkill /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
browservariable is defined in a scope where thecatchblock can see it. If you defineconst browserinside thetryblock, it will be unavailable in thecatchblock.
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.