Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

cancel all playwright async tasks on exit

Nick Sweeting502d8d157945
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 6a0af8edd..1c97777bb 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -432,6 +432,20 @@ class BrowserSession(BaseModel):
except Exception as e:
self.logger.debug(f'Error stopping playwright: {type(e).__name__}: {e}')
self.playwright = None
+ finally:
+ # Ensure playwright tasks are cancelled
+ try:
+ loop = asyncio.get_event_loop()
+ if loop and not loop.is_closed():
+ all_tasks = asyncio.all_tasks(loop)
+ for task in all_tasks:
+ if task.done():
+ continue
+ coro_str = str(task)
+ if 'Connection.run' in coro_str and 'playwright' in coro_str:
+ task.cancel()
+ except Exception:
+ pass
self._reset_connection_state()