Finish Firefox Runs with Playwright Stealth Plugins
In this article
This guide shows you how to properly close or "finish" Firefox browser runs when using Playwright with stealth plugins. The goal is to ensure your automation scripts exit cleanly, release system resources, and avoid leaving orphaned processes that can interfere with future runs or trigger detection. You'll learn the correct order of operations, how to handle browser contexts, and how to integrate stealth plugin cleanup.
What You'll Need
- Node.js (or Python) installed on your system
- Playwright installed in your project (
npm install playwrightorpip install playwright) - A stealth plugin such as
playwright-extrawithpuppeteer-extra-plugin-stealth(for Playwright compatibility) orplaywright-stealth(if using a compatible fork) - Firefox browser installed via Playwright (
npx playwright install firefox) - Basic understanding of async/await in JavaScript or asyncio in Python
Step-by-Step
- Install and import the stealth plugin correctly. For JavaScript, use
const { chromium } = require('playwright-extra');andconst stealth = require('puppeteer-extra-plugin-stealth')();thenchromium.use(stealth);. For Firefox, you must use thefirefoxexport from playwright-extra:const { firefox } = require('playwright-extra');. In Python, usefrom playwright_stealth import stealth_asyncand apply it to the page. - Launch the browser with the stealth plugin applied. In JavaScript:
const browser = await firefox.launch({ headless: false });(or headless: true if you prefer). In Python, launch normally and then apply stealth to each page:await stealth_async(page). - Create a new browser context. Use
const context = await browser.newContext();to get a clean session. This is important because stealth plugins often modify the user agent and other fingerprints per context. - Open a page and perform your automation.
const page = await context.newPage();then navigate to your target URL. Run your tests or scraping logic. Ensure you usetry/finallyortry/catchblocks to guarantee cleanup even if errors occur. - Close the page explicitly. After your actions, call
await page.close();to free up memory. This is optional but helps with large runs. - Close the context.
await context.close();This ends the browser session, clears cookies, and removes temporary files. It's essential to close the context before the browser to avoid leaks. - Close the browser. Finally,
await browser.close();This terminates the Firefox process. In JavaScript, this is usually done in afinallyblock to ensure it runs even if an error occurred earlier. - Handle process exit gracefully. If you're using Node.js, you may need to call
process.exit(0)after closing to ensure no lingering handles keep the event loop alive. In Python, ensure your script naturally ends or usesys.exit(). - Verify no orphaned processes. After the script finishes, check your system's process list (e.g.,
ps aux | grep firefoxon Linux/macOS, or Task Manager on Windows). There should be no remaining Firefox processes related to your run.
Common Mistakes
- Forgetting to close the context. Many developers close only the browser, but the context holds resources. Always close the context first.
- Using the wrong browser export. Playwright-extra's default export is Chromium. If you try to launch Firefox with
chromium.launch(), it will fail. Usefirefox.launch(). - Not using try/finally. If an error occurs mid-run, the browser may never close, leaving orphaned processes. Always wrap your automation in a
try/finallyblock. - Calling
browser.close()beforecontext.close(). This can cause unexpected behavior and may not release all resources. Follow the order: page → context → browser. - Ignoring async errors. If a promise rejects and you don't catch it, the script may exit without cleanup. Use
process.on('unhandledRejection')or similar to catch these.
Tips
- Use a helper function. Create a
runFirefox()function that encapsulates launch, context creation, and cleanup. This makes your code reusable and less error-prone. - Set a timeout for cleanup. In case the browser hangs, use
browser.close({ timeout: 5000 })(if supported) or a manual timer to force exit. - Run Firefox in headless mode for CI. Headless mode is faster and uses fewer resources, but stealth plugins may behave differently. Test both modes.
- Keep the stealth plugin up to date. Firefox updates frequently, and stealth plugins need to match to avoid detection. Check for updates regularly.
- Use a fresh context per run. This prevents data leakage between runs and ensures a clean fingerprint each time.
Troubleshooting
Firefox process remains after script ends. This usually means browser.close() was not called or threw an error. Add a finally block and log any errors. If the process persists, kill it manually (e.g., pkill firefox on Linux, or taskkill /F /IM firefox.exe on Windows) and fix the code.
Error: "BrowserType.launch: Executable doesn't exist" You haven't installed Firefox for Playwright. Run npx playwright install firefox to download it.
Stealth plugin not working on Firefox. Some stealth plugins are designed for Chromium only. Verify that the plugin explicitly supports Firefox. If not, consider using a different plugin or using Playwright's built-in firefox.launch({ firefoxUserPrefs }) to tweak settings manually.
Script hangs on context.close(). This can happen if there are pending network requests. Force close by calling context.close({ timeout: 3000 }) or cancel all pages first.
Memory leak across runs. Ensure you are not creating multiple browsers in a loop without closing them. Reuse a single browser instance if possible, and always close contexts after each run.
Frequently Asked Questions
Do I need to close the page before the context?
Not strictly, but closing the page first is cleaner and frees memory earlier. The context.close() will close all pages anyway.
Can I reuse a browser instance across multiple runs?
Yes, you can launch the browser once and create/close contexts for each run. This is more efficient and reduces startup time. Just ensure you close the browser at the end of your script.
What is the difference between browser.close() and process.exit()?
browser.close() gracefully shuts down the browser and releases resources. process.exit() forcibly terminates the Node.js process, which can skip cleanup. Use browser.close() first, then let the script exit naturally.
Does stealth plugin affect the closing process?
No, stealth plugins mainly modify the browser's fingerprint at launch. They do not interfere with closing. However, if the plugin uses global hooks, ensure you call chromium.use(stealth) only once.
How do I handle multiple pages in one context?
You can open multiple pages in the same context. When closing, you can close each page individually or just close the context, which will close all pages automatically.
Is it safe to use process.exit() after browser.close()?
Yes, it's safe and often recommended to avoid lingering event loop handles. But ensure browser.close() has resolved before calling process.exit().