Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Enhance dialog handling in watchdogs
Magnus Müller5faba663e2d5
diff --git a/browser_use/browser/watchdogs/default_action_watchdog.py b/browser_use/browser/watchdogs/default_action_watchdog.pyindex ff678b6eb..30305b0c9 100644--- a/browser_use/browser/watchdogs/default_action_watchdog.py+++ b/browser_use/browser/watchdogs/default_action_watchdog.py@@ -648,6 +648,7 @@ class DefaultActionWatchdog(BaseWatchdog):self.logger.debug('⏱️ Mouse up timed out (possibly due to lag or dialog popup), continuing...')self.logger.debug('🖱️ Clicked successfully using x,y coordinates')+# Return coordinates as dict for metadatareturn {'click_x': center_x, 'click_y': center_y}@@ -671,14 +672,27 @@ class DefaultActionWatchdog(BaseWatchdog):},session_id=session_id,)++ # Small delay for dialog dismissal+ await asyncio.sleep(0.1)+return Noneexcept Exception as js_e:self.logger.error(f'CDP JavaScript click also failed: {js_e}')raise Exception(f'Failed to click element: {e}')finally:- # always re-focus back to original top-level page session context in case click opened a new tab/popup/window/dialog/etc.- cdp_session = await self.browser_session.get_or_create_cdp_session(focus=True)- await cdp_session.cdp_client.send.Runtime.runIfWaitingForDebugger(session_id=cdp_session.session_id)+ # Always re-focus back to original top-level page session context in case click opened a new tab/popup/window/dialog/etc.+ # Use timeout to prevent hanging if dialog is blocking+ try:+ cdp_session = await asyncio.wait_for(self.browser_session.get_or_create_cdp_session(focus=True), timeout=3.0)+ await asyncio.wait_for(+ cdp_session.cdp_client.send.Runtime.runIfWaitingForDebugger(session_id=cdp_session.session_id),+ timeout=2.0,+ )+ except TimeoutError:+ self.logger.debug('⏱️ Refocus after click timed out (page may be blocked by dialog). Continuing...')+ except Exception as e:+ self.logger.debug(f'⚠️ Refocus error (non-critical): {type(e).__name__}: {e}')except URLNotAllowedError as e:raise ediff --git a/browser_use/browser/watchdogs/popups_watchdog.py b/browser_use/browser/watchdogs/popups_watchdog.pyindex 32dc6419d..20904dfac 100644--- a/browser_use/browser/watchdogs/popups_watchdog.py+++ b/browser_use/browser/watchdogs/popups_watchdog.py@@ -41,9 +41,22 @@ class PopupsWatchdog(BaseWatchdog):target_id, focus=False) # don't auto-focus new tabs! sometimes we need to open tabs in background+ # CRITICAL: Enable Page domain to receive dialog events+ try:+ await cdp_session.cdp_client.send.Page.enable(session_id=cdp_session.session_id)+ self.logger.debug(f'✅ Enabled Page domain for session {cdp_session.session_id[-8:]}')+ except Exception as e:+ self.logger.warning(f'Failed to enable Page domain: {e}')+# Also register for the root CDP client to catch dialogs from any frameif self.browser_session._cdp_client_root:self.logger.debug('📌 Also registering handler on root CDP client')+ try:+ # Enable Page domain on root client too+ await self.browser_session._cdp_client_root.send.Page.enable()+ self.logger.debug('✅ Enabled Page domain on root CDP client')+ except Exception as e:+ self.logger.warning(f'Failed to enable Page domain on root: {e}')# Set up async handler for JavaScript dialogs - accept immediately without event dispatchasync def handle_dialog(event_data, session_id: str | None = None):@@ -52,39 +65,51 @@ class PopupsWatchdog(BaseWatchdog):dialog_type = event_data.get('type', 'alert')message = event_data.get('message', '')- self.logger.info(f"🔔 JavaScript {dialog_type} dialog: '{message[:100]}' - attempting to accept...")+ # Choose action based on dialog type:+ # - alert: accept=true (click OK to dismiss)+ # - confirm: accept=true (click OK to proceed - safer for automation)+ # - prompt: accept=false (click Cancel since we can't provide input)+ # - beforeunload: accept=true (allow navigation)+ should_accept = dialog_type in ('alert', 'confirm', 'beforeunload')++ action_str = 'accepting (OK)' if should_accept else 'dismissing (Cancel)'+ self.logger.info(f"🔔 JavaScript {dialog_type} dialog: '{message[:100]}' - {action_str}...")- self.logger.debug('Trying all approaches to accept dialog...')+ dismissed = False- # Approach 1: Use the session that detected the dialog+ # Approach 1: Use the session that detected the dialog (most reliable)if self.browser_session._cdp_client_root and session_id:try:- self.logger.debug(f'🔄 Approach 1: Using session {session_id}')+ self.logger.debug(f'🔄 Approach 1: Using detecting session {session_id[-8:]}')await asyncio.wait_for(self.browser_session._cdp_client_root.send.Page.handleJavaScriptDialog(- params={'accept': True},+ params={'accept': should_accept},session_id=session_id,),- timeout=0.25,+ timeout=0.5,)+ dismissed = True+ self.logger.info('✅ Dialog handled successfully via detecting session')except (TimeoutError, Exception) as e:- pass+ self.logger.debug(f'Approach 1 failed: {type(e).__name__}')# Approach 2: Try with current agent focus session- if self.browser_session._cdp_client_root and self.browser_session.agent_focus:+ if not dismissed and self.browser_session._cdp_client_root and self.browser_session.agent_focus:try:self.logger.debug(- f'🔄 Approach 2: Using agent focus session {self.browser_session.agent_focus.session_id}'+ f'🔄 Approach 2: Using agent focus session {self.browser_session.agent_focus.session_id[-8:]}')await asyncio.wait_for(self.browser_session._cdp_client_root.send.Page.handleJavaScriptDialog(- params={'accept': True},+ params={'accept': should_accept},session_id=self.browser_session.agent_focus.session_id,),- timeout=0.25,+ timeout=0.5,)+ dismissed = True+ self.logger.info('✅ Dialog handled successfully via agent focus session')except (TimeoutError, Exception) as e:- pass+ self.logger.debug(f'Approach 2 failed: {type(e).__name__}')except Exception as e:self.logger.error(f'❌ Critical error in dialog handler: {type(e).__name__}: {e}')