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
popup works
Magnus Müller3a7ae8d8d638
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.pyindex 24c80aee5..ba6e12925 100644--- a/browser_use/browser/events.py+++ b/browser_use/browser/events.py@@ -510,7 +510,7 @@ class DialogOpenedEvent(BaseEvent):dialog_type: str # 'alert', 'confirm', 'prompt', or 'beforeunload'message: strurl: str- frame_id: str+ frame_id: str | None = None # Can be None when frameId is not provided by CDP# target_id: TargetID # TODO: add this to avoid needing target_id_from_frame() laterdiff --git a/browser_use/browser/watchdogs/popups_watchdog.py b/browser_use/browser/watchdogs/popups_watchdog.pyindex f517838a2..819dcf8fa 100644--- a/browser_use/browser/watchdogs/popups_watchdog.py+++ b/browser_use/browser/watchdogs/popups_watchdog.py@@ -6,16 +6,16 @@ from typing import ClassVarfrom bubus import BaseEventfrom pydantic import PrivateAttr-from browser_use.browser.events import DialogOpenedEvent, TabCreatedEvent+from browser_use.browser.events import TabCreatedEventfrom browser_use.browser.watchdog_base import BaseWatchdogclass PopupsWatchdog(BaseWatchdog):- """Handles JavaScript dialogs (alert, confirm, prompt) by automatically accepting them."""+ """Handles JavaScript dialogs (alert, confirm, prompt) by automatically dismissing them immediately."""# Events this watchdog listens to and emits- LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [TabCreatedEvent, DialogOpenedEvent]- EMITS: ClassVar[list[type[BaseEvent]]] = [DialogOpenedEvent]+ LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [TabCreatedEvent]+ EMITS: ClassVar[list[type[BaseEvent]]] = []# Track which targets have dialog handlers registered_dialog_listeners_registered: set[str] = PrivateAttr(default_factory=set)@@ -36,52 +36,75 @@ class PopupsWatchdog(BaseWatchdog):self.logger.debug(f'📌 Starting dialog handler setup for target {target_id}')try:+ # Get all CDP sessions for this target and any child framescdp_session = await self.browser_session.get_or_create_cdp_session(target_id, focus=False) # don't auto-focus new tabs! sometimes we need to open tabs in background- # Set up async handler for JavaScript dialogs - now we can handle them immediately!- async def handle_dialog(event_data, session_id: str | None = None):- """Handle JavaScript dialog events - accept immediately and dispatch event."""- self.logger.debug(f'🚨 DIALOG EVENT RECEIVED: {event_data}, session_id={session_id}')-- dialog_type = event_data.get('type', 'alert')- message = event_data.get('message', '')- url = event_data.get('url')- frame_id = event_data.get('frameId')-- self.logger.debug(f"🔔 JavaScript {dialog_type} dialog detected: '{message[:50]}...' - accepting immediately")-- # Dispatch the event first so tests can observe it- event = self.browser_session.event_bus.dispatch(- DialogOpenedEvent(- frame_id=frame_id,- dialog_type=dialog_type,- message=message,- url=url,- )- )- await event.event_result(raise_if_none=False, raise_if_any=True, timeout=5.0)+ # Also register for the root CDP client to catch dialogs from any frame+ if self.browser_session._cdp_client_root:+ self.logger.debug('📌 Also registering handler on root CDP client')- # Accept the dialog immediately to unblock the browser+ # Set up async handler for JavaScript dialogs - accept immediately without event dispatch+ async def handle_dialog(event_data, session_id: str | None = None):+ """Handle JavaScript dialog events - accept immediately."""try:+ dialog_type = event_data.get('type', 'alert')+ message = event_data.get('message', '')++ self.logger.info(f"🔔 JavaScript {dialog_type} dialog: '{message[:100]}' - attempting to dismiss...")++ self.logger.debug('Trying all approaches to dismiss dialog...')++ # Approach 1: Use the session that detected the dialogif self.browser_session._cdp_client_root and session_id:- self.logger.debug('🔄 Sending handleJavaScriptDialog command')- await self.browser_session._cdp_client_root.send.Page.handleJavaScriptDialog(- params={'accept': True},- session_id=session_id,- )- self.logger.info('✅ Dialog accepted successfully')- else:- self.logger.error('Cannot accept dialog - CDP client or session not available')+ try:+ self.logger.debug(f'🔄 Approach 1: Using session {session_id}')+ await asyncio.wait_for(+ self.browser_session._cdp_client_root.send.Page.handleJavaScriptDialog(+ params={'accept': True},+ session_id=session_id,+ ),+ timeout=0.25,+ )+ except (asyncio.TimeoutError, Exception) as e:+ pass++ # Approach 2: Try with current agent focus session+ if self.browser_session.agent_focus:+ try:+ self.logger.debug(+ f'🔄 Approach 2: Using agent focus session {self.browser_session.agent_focus.session_id}'+ )+ await asyncio.wait_for(+ self.browser_session._cdp_client_root.send.Page.handleJavaScriptDialog(+ params={'accept': True},+ session_id=self.browser_session.agent_focus.session_id,+ ),+ timeout=0.25,+ )+ except (asyncio.TimeoutError, Exception) as e:+ pass++ # await self._post_dialog_recovery()+except Exception as e:- self.logger.error(f'Failed to accept dialog: {e}')+ self.logger.error(f'❌ Critical error in dialog handler: {type(e).__name__}: {e}')+ # Register handler on the specific sessioncdp_session.cdp_client.register.Page.javascriptDialogOpening(handle_dialog) # type: ignore[arg-type]self.logger.debug(f'Successfully registered Page.javascriptDialogOpening handler for session {cdp_session.session_id}')+ # Also register on root CDP client to catch dialogs from any frame+ if hasattr(self.browser_session._cdp_client_root, 'register'):+ try:+ self.browser_session._cdp_client_root.register.Page.javascriptDialogOpening(handle_dialog) # type: ignore[arg-type]+ self.logger.debug('Successfully registered dialog handler on root CDP client for all frames')+ except Exception as root_error:+ self.logger.warning(f'Failed to register on root CDP client: {root_error}')+# Mark this target as having dialog handling set upself._dialog_listeners_registered.add(target_id)@@ -90,53 +113,31 @@ class PopupsWatchdog(BaseWatchdog):except Exception as e:self.logger.warning(f'Failed to set up dialog handling for tab {target_id}: {e}')- async def on_DialogOpenedEvent(self, event: DialogOpenedEvent) -> None:- """Handle the async closing of JavaScript dialogs."""- self.logger.debug(- f'📋 on_DialogOpenedEvent called with frame_id={event.frame_id} url={event.url} message={event.message}'- )+ async def _post_dialog_recovery(self) -> None:+ """Perform post-dialog recovery to ensure browser session continues normally."""+ try:+ self.logger.debug('🔄 Starting post-dialog recovery...')- assert self.browser_session.agent_focus is not None, 'Agent focus not set when handling DialogOpenedEvent'+ # Small delay to let browser process dialog dismissal+ await asyncio.sleep(0.1)- current_focus_url = self.browser_session.agent_focus.url- current_focus_target_id = self.browser_session.agent_focus.target_id+ # Ensure agent focus is still valid+ if self.browser_session.agent_focus:+ try:+ # Try to reactivate the current target to ensure it's responsive+ await self.browser_session._cdp_client_root.send.Target.activateTarget(+ params={'targetId': self.browser_session.agent_focus.target_id}+ )+ self.logger.debug('✅ Reactivated agent focus target after dialog dismissal')+ except Exception as reactivate_error:+ self.logger.warning(f'Failed to reactivate target after dialog: {reactivate_error}')- cdp_session = await asyncio.wait_for(self.browser_session.cdp_client_for_frame(event.frame_id), timeout=5.0)- try:- # delay to look more human before auto-closing, some popular antibot fingerprint tests check for modals closing too fast- await asyncio.sleep(0.25)- assert self.browser_session._cdp_client_root- # self.browser_session._cdp_client_root.register.Page.javascriptDialogClosed(lambda *args: None)- await asyncio.wait_for(- self.browser_session._cdp_client_root.send.Page.handleJavaScriptDialog(- params={'accept': True},- session_id=cdp_session.session_id,- ),- timeout=5.0,- )- # CRITICAL: you must re-focus (Target.activateTarget()) after handling the dialog, otherwise the browser will crash ~5 seconds later- await self.browser_session.get_or_create_cdp_session(target_id=current_focus_target_id, focus=True)- self.logger.info('✅ JS dialog popup handled successfully')-- # graveyard of past attempts:- # # new_target = await self.browser_session._cdp_client_root.send.Target.createTarget(params={'url': current_focus_url})- # # self.browser_session.agent_focus = await self.browser_session.get_or_create_cdp_session(target_id=new_target.get('targetId'), new_socket=True, focus=True)- # # raise NotImplementedError('TODO: figure out why this requires a hard refresh and new socket to avoid crashing the entire browser on JS dialogs')- # await asyncio.sleep(0.2)- # await asyncio.wait_for(- # self.browser_session._cdp_client_root.send.Runtime.evaluate(- # params={'expression': '1'},- # session_id=cdp_session.session_id,- # ),- # timeout=5.0,- # )- # # self.browser_session.agent_focus = await self.browser_session.get_or_create_cdp_session(current_focus.target_id, focus=True, new_socket=True)- # # assert await self.browser_session.agent_focus.cdp_client.send.Page.getFrameTree(session_id=self.browser_session.agent_focus.session_id) is not None, "Agent focus not set after handling dialog"- except Exception as e:- self.logger.error(f'Failed to handle JavaScript dialog gracefully: {e}')- # raise- # finally:- # self.event_bus.dispatch(AgentFocusChangedEvent(- # target_id=current_focus_target_id,- # url=self.browser_session.agent_focus.url,- # ))+ # Clear any cached browser state that might be stale+ if hasattr(self.browser_session, '_cached_browser_state'):+ self.browser_session._cached_browser_state = None+ self.logger.debug('🧹 Cleared cached browser state')++ self.logger.info('✅ Post-dialog recovery completed')++ except Exception as recovery_error:+ self.logger.error(f'❌ Post-dialog recovery failed: {recovery_error}')