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
fix cross-origin iframe handling
Nick Sweetingeedf0e7aa8d0
diff --git a/browser_use/browser/aboutblank_watchdog.py b/browser_use/browser/aboutblank_watchdog.pyindex f83e26dfa..59f8da81e 100644--- a/browser_use/browser/aboutblank_watchdog.py+++ b/browser_use/browser/aboutblank_watchdog.py@@ -16,7 +16,6 @@ from browser_use.browser.events import (TabCreatedEvent,)from browser_use.browser.watchdog_base import BaseWatchdog-from browser_use.utils import loggerif TYPE_CHECKING:pass@@ -73,7 +72,7 @@ class AboutBlankWatchdog(BaseWatchdog):# Use _cdp_get_all_pages for quick check without fetching titlespage_targets = await self.browser_session._cdp_get_all_pages()if len(page_targets) <= 1:- logger.info('[AboutBlankWatchdog] Last tab closing, creating new about:blank tab to avoid closing entire browser')+ self.logger.info('[AboutBlankWatchdog] Last tab closing, creating new about:blank tab to avoid closing entire browser')# Create the animation tab since no tabs should remainnavigate_event = self.event_bus.dispatch(NavigateToUrlEvent(url='about:blank', new_tab=True))await navigate_event@@ -125,7 +124,7 @@ class AboutBlankWatchdog(BaseWatchdog):passexcept Exception as e:- logger.error(f'[AboutBlankWatchdog] Error ensuring about:blank tab: {e}')+ self.logger.error(f'[AboutBlankWatchdog] Error ensuring about:blank tab: {e}')async def _show_dvd_screensaver_on_about_blank_tabs(self) -> None:"""Show DVD screensaver on all new tab pages."""@@ -151,7 +150,7 @@ class AboutBlankWatchdog(BaseWatchdog):await self._show_dvd_screensaver_loading_animation_cdp(target_id, browser_session_id)except Exception as e:- logger.error(f'[AboutBlankWatchdog] Error showing DVD screensaver: {e}')+ self.logger.error(f'[AboutBlankWatchdog] Error showing DVD screensaver: {e}')async def _show_dvd_screensaver_loading_animation_cdp(self, target_id: str, browser_session_label: str) -> None:"""@@ -299,5 +298,5 @@ class AboutBlankWatchdog(BaseWatchdog):self.event_bus.dispatch(AboutBlankDVDScreensaverShownEvent(tab_index=tab_index))except Exception as e:- logger.error(f'[AboutBlankWatchdog] Error injecting DVD screensaver: {e}')+ self.logger.error(f'[AboutBlankWatchdog] Error injecting DVD screensaver: {e}')diff --git a/browser_use/browser/crash_watchdog.py b/browser_use/browser/crash_watchdog.pyindex 81e2370a4..1ff79a286 100644--- a/browser_use/browser/crash_watchdog.py+++ b/browser_use/browser/crash_watchdog.py@@ -15,7 +15,6 @@ from browser_use.browser.events import (TargetCrashedEvent,)from browser_use.browser.watchdog_base import BaseWatchdog-from browser_use.utils import loggerif TYPE_CHECKING:pass@@ -114,10 +113,10 @@ class CrashWatchdog(BaseWatchdog):targets = await cdp_client.send.Target.getTargets()target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)if target_info:- logger.debug(f'[CrashWatchdog] Added target to monitoring: {target_info.get("url", "unknown")}')+ self.logger.debug(f'[CrashWatchdog] Added target to monitoring: {target_info.get("url", "unknown")}')except Exception as e:- logger.warning(f'[CrashWatchdog] Failed to attach to target {target_id}: {e}')+ self.logger.warning(f'[CrashWatchdog] Failed to attach to target {target_id}: {e}')async def _on_request_cdp(self, event: dict) -> None:"""Track new network request from CDP event."""@@ -139,7 +138,7 @@ class CrashWatchdog(BaseWatchdog):if request_id in self._active_requests:elapsed = time.time() - self._active_requests[request_id].start_timeresponse = event.get('response', {})- logger.debug(f'[CrashWatchdog] Request completed in {elapsed:.2f}s: {response.get("url", "")[:50]}...')+ self.logger.debug(f'[CrashWatchdog] Request completed in {elapsed:.2f}s: {response.get("url", "")[:50]}...')# Don't remove yet - wait for loadingFinisheddef _on_request_failed_cdp(self, event: dict) -> None:@@ -147,7 +146,7 @@ class CrashWatchdog(BaseWatchdog):request_id = event.get('requestId', '')if request_id in self._active_requests:elapsed = time.time() - self._active_requests[request_id].start_time- logger.debug(f'[CrashWatchdog] Request failed after {elapsed:.2f}s: {self._active_requests[request_id].url[:50]}...')+ self.logger.debug(f'[CrashWatchdog] Request failed after {elapsed:.2f}s: {self._active_requests[request_id].url[:50]}...')del self._active_requests[request_id]def _on_request_finished_cdp(self, event: dict) -> None:@@ -163,7 +162,7 @@ class CrashWatchdog(BaseWatchdog):target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)target_url = target_info.get('url', 'unknown') if target_info else 'unknown'- logger.error(f'[CrashWatchdog] Target crashed: {target_url}')+ self.logger.error(f'[CrashWatchdog] Target crashed: {target_url}')# Get tab indextab_index = await self.browser_session.get_tab_index(target_id)@@ -209,7 +208,7 @@ class CrashWatchdog(BaseWatchdog):# Set up browser crash handlerdef on_browser_crash(event):- logger.error('[CrashWatchdog] Browser crash detected via CDP')+ self.logger.error('[CrashWatchdog] Browser crash detected via CDP')self.event_bus.dispatch(BrowserErrorEvent(error_type='BrowserCrash',@@ -219,13 +218,13 @@ class CrashWatchdog(BaseWatchdog):)# Note: Browser.crash event might not exist, using Inspector.targetCrashed instead- logger.debug('[CrashWatchdog] π₯ CDP crash detection enabled')+ self.logger.debug('[CrashWatchdog] π₯ CDP crash detection enabled')except Exception:# Browser domain not available, rely on target-level monitoringpassexcept Exception as e:- logger.warning(f'[CrashWatchdog] Failed to set up CDP crash detection: {e}')+ self.logger.warning(f'[CrashWatchdog] Failed to set up CDP crash detection: {e}')async def _stop_monitoring(self) -> None:"""Stop the monitoring loop."""@@ -235,7 +234,7 @@ class CrashWatchdog(BaseWatchdog):await self._monitoring_taskexcept asyncio.CancelledError:pass- logger.debug('[CrashWatchdog] Monitoring loop stopped')+ self.logger.debug('[CrashWatchdog] Monitoring loop stopped')# Clean up CDP sessionsif self._cdp_sessions:@@ -260,7 +259,7 @@ class CrashWatchdog(BaseWatchdog):except asyncio.CancelledError:breakexcept Exception as e:- logger.error(f'[CrashWatchdog] Error in monitoring loop: {e}')+ self.logger.error(f'[CrashWatchdog] Error in monitoring loop: {e}')async def _check_network_timeouts(self) -> None:"""Check for network requests exceeding timeout."""@@ -269,13 +268,13 @@ class CrashWatchdog(BaseWatchdog):# Debug loggingif self._active_requests:- logger.debug(+ self.logger.debug(f'[CrashWatchdog] Checking {len(self._active_requests)} active requests for timeouts (threshold: {self.network_timeout_seconds}s)')for request_id, tracker in self._active_requests.items():elapsed = current_time - tracker.start_time- logger.debug(+ self.logger.debug(f'[CrashWatchdog] Request {tracker.url[:30]}... elapsed: {elapsed:.1f}s, timeout: {self.network_timeout_seconds}s')if elapsed >= self.network_timeout_seconds:@@ -283,7 +282,7 @@ class CrashWatchdog(BaseWatchdog):# Emit events for timed out requestsfor request_id, tracker in timed_out_requests:- logger.warning(+ self.logger.warning(f'[CrashWatchdog] Network request timeout after {self.network_timeout_seconds}s: 'f'{tracker.method} {tracker.url[:100]}...')@@ -312,7 +311,7 @@ class CrashWatchdog(BaseWatchdog):# Try a simple CDP command to check connectionawait asyncio.wait_for(cdp_client.send.Target.getTargets(), timeout=2.0)except (asyncio.TimeoutError, Exception) as e:- logger.error(f'[CrashWatchdog] Browser connection check failed: {e}')+ self.logger.error(f'[CrashWatchdog] Browser connection check failed: {e}')self.event_bus.dispatch(BrowserErrorEvent(error_type='BrowserDisconnected', message='Browser disconnected unexpectedly', details={}))@@ -323,7 +322,7 @@ class CrashWatchdog(BaseWatchdog):if proc := self.browser_session._local_browser_watchdog._subprocess:try:if proc.status() in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD):- logger.error(f'[CrashWatchdog] Browser process {proc.pid} has crashed')+ self.logger.error(f'[CrashWatchdog] Browser process {proc.pid} has crashed')self.event_bus.dispatch(BrowserErrorEvent(error_type='BrowserProcessCrashed',@@ -368,13 +367,13 @@ class CrashWatchdog(BaseWatchdog):dead_targets.append(target)except Exception as e:- logger.error(f'[CrashWatchdog] Error checking target health: {e}')+ self.logger.error(f'[CrashWatchdog] Error checking target health: {e}')return# Report unresponsive targetsfor target in unresponsive_targets:target_url = target.get('url', 'unknown')- logger.warning(f'[CrashWatchdog] Target unresponsive: {target_url}')+ self.logger.warning(f'[CrashWatchdog] Target unresponsive: {target_url}')tab_index = await self.browser_session.get_tab_index(target['targetId'])self.event_bus.dispatch(@@ -452,19 +451,19 @@ class CrashWatchdog(BaseWatchdog):"""Trigger a browser crash for testing (requires CDP)."""try:cdp_client = self.browser_session.cdp_client- logger.warning('[CrashWatchdog] Triggering browser crash for testing...')+ self.logger.warning('[CrashWatchdog] Triggering browser crash for testing...')await cdp_client.send.Browser.crash()except Exception as e:- logger.error(f'[CrashWatchdog] Failed to trigger browser crash: {e}')+ self.logger.error(f'[CrashWatchdog] Failed to trigger browser crash: {e}')async def trigger_gpu_crash(self) -> None:"""Trigger a GPU process crash for testing (requires CDP)."""try:cdp_client = self.browser_session.cdp_client- logger.warning('[CrashWatchdog] Triggering GPU crash for testing...')+ self.logger.warning('[CrashWatchdog] Triggering GPU crash for testing...')await cdp_client.send.Browser.crashGpuProcess()except Exception as e:- logger.error(f'[CrashWatchdog] Failed to trigger GPU crash: {e}')+ self.logger.error(f'[CrashWatchdog] Failed to trigger GPU crash: {e}')async def trigger_target_crash(self, target_id: str) -> None:"""Trigger a target crash for testing."""@@ -476,7 +475,7 @@ class CrashWatchdog(BaseWatchdog):target_info = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)target_url = target_info.get('url', 'unknown') if target_info else 'unknown'- logger.warning(f'[CrashWatchdog] Triggering target crash for testing on: {target_url}')+ self.logger.warning(f'[CrashWatchdog] Triggering target crash for testing on: {target_url}')# Attach to targetsession = await cdp_client.send.Target.attachToTarget(@@ -490,4 +489,4 @@ class CrashWatchdog(BaseWatchdog):# Detachawait cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})except Exception as e:- logger.error(f'[CrashWatchdog] Failed to trigger target crash: {e}')\ No newline at end of file+ self.logger.error(f'[CrashWatchdog] Failed to trigger target crash: {e}')\ No newline at end of filediff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.pyindex aab42d510..cb3d45d7e 100644--- a/browser_use/browser/default_action_watchdog.py+++ b/browser_use/browser/default_action_watchdog.py@@ -20,7 +20,6 @@ from browser_use.browser.events import ()from browser_use.browser.views import BrowserError, URLNotAllowedErrorfrom browser_use.browser.watchdog_base import BaseWatchdog-from browser_use.utils import loggerif TYPE_CHECKING:pass@@ -42,7 +41,7 @@ class DefaultActionWatchdog(BaseWatchdog):# Check if element is a file input (should not be clicked)if self.browser_session.is_file_input(element_node):msg = f'Index {index_for_logging} - has an element which opens file upload dialog. To upload files please use a specific function to upload files'- logger.info(msg)+ self.logger.info(msg)self.event_bus.dispatch(BrowserErrorEvent(error_type='FileInputElement',@@ -60,18 +59,18 @@ class DefaultActionWatchdog(BaseWatchdog):# Build success messageif download_path:msg = f'Downloaded file to {download_path}'- logger.info(f'πΎ {msg}')+ self.logger.info(f'πΎ {msg}')else:msg = f'Clicked button with index {index_for_logging}: {element_node.get_all_children_text(max_depth=2)}'- logger.info(f'π±οΈ {msg}')- logger.debug(f'Element xpath: {element_node.xpath}')+ self.logger.info(f'π±οΈ {msg}')+ self.logger.debug(f'Element xpath: {element_node.xpath}')# Check if a new tab was openedcurrent_target_ids = await self.browser_session.target_idsif len(current_target_ids) > len(initial_target_ids):new_tab_msg = 'New tab opened - switching to it'msg += f' - {new_tab_msg}'- logger.info(f'π {new_tab_msg}')+ self.logger.info(f'π {new_tab_msg}')# Switch to the last tab (newly created tab)from browser_use.browser.events import SwitchTabEvent@@ -101,8 +100,8 @@ class DefaultActionWatchdog(BaseWatchdog):await self._input_text_element_node_impl(element_node, event.text, event.clear_existing)# Log success- logger.info(f'β¨οΈ Typed "{event.text}" into element with index {index_for_logging}')- logger.debug(f'Element xpath: {element_node.xpath}')+ self.logger.info(f'β¨οΈ Typed "{event.text}" into element with index {index_for_logging}')+ self.logger.debug(f'Element xpath: {element_node.xpath}')except Exception as e:self.event_bus.dispatch(BrowserErrorEvent(@@ -140,14 +139,14 @@ class DefaultActionWatchdog(BaseWatchdog):# Try to scroll the element's containersuccess = await self._scroll_element_container(element_node, pixels)if success:- logger.info(f'π Scrolled element {index_for_logging} container {event.direction} by {event.amount} pixels')+ self.logger.info(f'π Scrolled element {index_for_logging} container {event.direction} by {event.amount} pixels')return# Perform target-level scrollawait self._scroll_with_cdp_gesture(pixels)# Log success- logger.info(f'π Scrolled {event.direction} by {event.amount} pixels')+ self.logger.info(f'π Scrolled {event.direction} by {event.amount} pixels')except Exception as e:self.event_bus.dispatch(BrowserErrorEvent(@@ -197,7 +196,7 @@ class DefaultActionWatchdog(BaseWatchdog):await cdp_client.send.DOM.scrollIntoViewIfNeeded(params={'backendNodeId': backend_node_id}, session_id=session_id)await asyncio.sleep(0.1) # Wait for scroll to completeexcept Exception as e:- logger.debug(f'Failed to scroll element into view: {e}')+ self.logger.debug(f'Failed to scroll element into view: {e}')# Set up download detection if downloads are enableddownload_path = None@@ -273,19 +272,19 @@ class DefaultActionWatchdog(BaseWatchdog):download_complete = Truebreakelif response['state'] == 'canceled':- logger.warning('Download was canceled')+ self.logger.warning('Download was canceled')breakexcept Exception:passawait asyncio.sleep(1)if download_complete and download_guid:- logger.info('β¬οΈ Download completed via CDP')+ self.logger.info('β¬οΈ Download completed via CDP')# Note: DownloadsWatchdog handles download tracking via eventsreturn f'download_{download_guid}' # Return guid as placeholderexcept TimeoutError:# No download triggered, normal click- logger.debug('No download triggered within timeout.')+ self.logger.debug('No download triggered within timeout.')# Wait for navigation/changesawait asyncio.sleep(0.5)@@ -294,7 +293,7 @@ class DefaultActionWatchdog(BaseWatchdog):return download_pathexcept Exception as e:- logger.warning(f'CDP click failed: {type(e).__name__}: {e}')+ self.logger.warning(f'CDP click failed: {type(e).__name__}: {e}')# Fall back to JavaScript click via CDPtry:result = await cdp_client.send.DOM.resolveNode(@@ -314,7 +313,7 @@ class DefaultActionWatchdog(BaseWatchdog):# Navigation is handled by NavigationWatchdog via eventsreturn Noneexcept Exception as js_e:- logger.error(f'CDP JavaScript click also failed: {js_e}')+ self.logger.error(f'CDP JavaScript click also failed: {js_e}')raise Exception(f'Failed to click element: {e}')except URLNotAllowedError as e:@@ -342,7 +341,7 @@ class DefaultActionWatchdog(BaseWatchdog):await cdp_client.send.DOM.scrollIntoViewIfNeeded(params={'backendNodeId': backend_node_id}, session_id=session_id)await asyncio.sleep(0.1)except Exception as e:- logger.debug(f'Failed to scroll element into view: {e}')+ self.logger.debug(f'Failed to scroll element into view: {e}')# Get object ID for the elementresult = await cdp_client.send.DOM.resolveNode(@@ -400,7 +399,7 @@ class DefaultActionWatchdog(BaseWatchdog):await asyncio.sleep(0.005)except Exception as e:- logger.error(f'Failed to input text via CDP: {type(e).__name__}: {e}')+ self.logger.error(f'Failed to input text via CDP: {type(e).__name__}: {e}')raise BrowserError(f'Failed to input text into element: {repr(element_node)}')async def _scroll_with_cdp_gesture(self, pixels: int) -> bool:@@ -442,11 +441,11 @@ class DefaultActionWatchdog(BaseWatchdog):session_id=session_id,)- logger.debug(f'π Scrolled via CDP mouse wheel: {pixels}px')+ self.logger.debug(f'π Scrolled via CDP mouse wheel: {pixels}px')return Trueexcept Exception as e:- logger.warning(f'β Scrolling via CDP failed: {type(e).__name__}: {e}')+ self.logger.warning(f'β Scrolling via CDP failed: {type(e).__name__}: {e}')return Falseasync def _scroll_element_container(self, element_node, pixels: int) -> bool:@@ -481,7 +480,7 @@ class DefaultActionWatchdog(BaseWatchdog):return Trueexcept Exception as e:- logger.debug(f'Failed to scroll element container via CDP: {e}')+ self.logger.debug(f'Failed to scroll element container via CDP: {e}')return Falseasync def _get_session_id_for_element(self, cdp_client: CDPClient, element_node) -> str | None:@@ -508,9 +507,9 @@ class DefaultActionWatchdog(BaseWatchdog):return session_id# If frame not found in targets, use main target session- logger.debug(f'Frame {element_node.frame_id} not found in targets, using main session')+ self.logger.debug(f'Frame {element_node.frame_id} not found in targets, using main session')except Exception as e:- logger.debug(f'Error getting frame session: {e}, using main session')+ self.logger.debug(f'Error getting frame session: {e}, using main session')# Use main target sessionreturn await self.browser_session.get_current_page_cdp_session_id()@@ -529,7 +528,7 @@ class DefaultActionWatchdog(BaseWatchdog):# Check if we can go backif current_index <= 0:- logger.warning('β οΈ Cannot go back - no previous entry in history')+ self.logger.warning('β οΈ Cannot go back - no previous entry in history')return# Navigate to the previous entry@@ -540,7 +539,7 @@ class DefaultActionWatchdog(BaseWatchdog):await asyncio.sleep(0.5)# Navigation is handled by NavigationWatchdog via events- logger.info(f'π Navigated back to {entries[current_index - 1]["url"]}')+ self.logger.info(f'π Navigated back to {entries[current_index - 1]["url"]}')except Exception as e:self.event_bus.dispatch(BrowserErrorEvent(@@ -563,7 +562,7 @@ class DefaultActionWatchdog(BaseWatchdog):# Check if we can go forwardif current_index >= len(entries) - 1:- logger.warning('β οΈ Cannot go forward - no next entry in history')+ self.logger.warning('β οΈ Cannot go forward - no next entry in history')return# Navigate to the next entry@@ -574,7 +573,7 @@ class DefaultActionWatchdog(BaseWatchdog):await asyncio.sleep(0.5)# Navigation is handled by NavigationWatchdog via events- logger.info(f'π Navigated forward to {entries[current_index + 1]["url"]}')+ self.logger.info(f'π Navigated forward to {entries[current_index + 1]["url"]}')except Exception as e:self.event_bus.dispatch(BrowserErrorEvent(@@ -597,7 +596,7 @@ class DefaultActionWatchdog(BaseWatchdog):await asyncio.sleep(1.0)# Navigation is handled by NavigationWatchdog via events- logger.info('π Target refreshed')+ self.logger.info('π Target refreshed')except Exception as e:self.event_bus.dispatch(BrowserErrorEvent(@@ -612,9 +611,9 @@ class DefaultActionWatchdog(BaseWatchdog):# Cap wait time at maximumactual_seconds = min(max(event.seconds, 0), event.max_seconds)if actual_seconds != event.seconds:- logger.info(f'π Waiting for {actual_seconds} seconds (capped from {event.seconds}s)')+ self.logger.info(f'π Waiting for {actual_seconds} seconds (capped from {event.seconds}s)')else:- logger.info(f'π Waiting for {actual_seconds} seconds')+ self.logger.info(f'π Waiting for {actual_seconds} seconds')await asyncio.sleep(actual_seconds)except Exception as e:@@ -701,7 +700,7 @@ class DefaultActionWatchdog(BaseWatchdog):session_id=session_id,)- logger.info(f'β¨οΈ Sent keys: {event.keys}')+ self.logger.info(f'β¨οΈ Sent keys: {event.keys}')except Exception as e:self.event_bus.dispatch(BrowserErrorEvent(@@ -736,7 +735,7 @@ class DefaultActionWatchdog(BaseWatchdog):session_id=session_id,)- logger.info(f'π Uploaded file {event.file_path} to element {index_for_logging}')+ self.logger.info(f'π Uploaded file {event.file_path} to element {index_for_logging}')except Exception as e:self.event_bus.dispatch(BrowserErrorEvent(@@ -789,13 +788,13 @@ class DefaultActionWatchdog(BaseWatchdog):await cdp_client.send.DOM.scrollIntoViewIfNeeded(params={'nodeId': node_id}, session_id=session_id)found = True- logger.info(f'π Scrolled to text: "{event.text}"')+ self.logger.info(f'π Scrolled to text: "{event.text}"')break# Clean up searchawait cdp_client.send.DOM.discardSearchResults(params={'searchId': search_id}, session_id=session_id)except Exception as e:- logger.debug(f'Search query failed: {query}, error: {e}')+ self.logger.debug(f'Search query failed: {query}, error: {e}')continueif not found:@@ -825,9 +824,9 @@ class DefaultActionWatchdog(BaseWatchdog):)if js_result.get('result', {}).get('value'):- logger.info(f'π Scrolled to text: "{event.text}" (via JS)')+ self.logger.info(f'π Scrolled to text: "{event.text}" (via JS)')else:- logger.warning(f'β οΈ Text not found: "{event.text}"')+ self.logger.warning(f'β οΈ Text not found: "{event.text}"')except Exception as e:self.event_bus.dispatch(BrowserErrorEvent(diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.pyindex beac74366..11798a88b 100644--- a/browser_use/browser/dom_watchdog.py+++ b/browser_use/browser/dom_watchdog.py@@ -240,7 +240,7 @@ class DOMWatchdog(BaseWatchdog):# Get serialized DOM tree using the servicestart = time.time()self.current_dom_state, self.enhanced_dom_tree, timing_info = await self._dom_service.get_serialized_dom_tree(- previous_cached_state=event.previous_state+ previous_cached_state=previous_state)end = time.time()diff --git a/browser_use/browser/events.py b/browser_use/browser/events.pyindex 0e0102937..bcfb4e27e 100644--- a/browser_use/browser/events.py+++ b/browser_use/browser/events.py@@ -190,18 +190,6 @@ class GetCookiesEvent(BaseEvent):# ============================================================================-class BuildDOMTreeEvent(BaseEvent):- """Build and serialize the DOM tree for the current page.-- Returns SerializedDOMState with the DOM tree ready for LLM consumption.- """-- previous_state: Any | None = None # SerializedDOMState, but avoid circular import---# ============================================================================--class BrowserConnectedEvent(BaseEvent):"""Browser has started/connected."""diff --git a/browser_use/browser/local_browser_watchdog.py b/browser_use/browser/local_browser_watchdog.pyindex 39b5ae011..e1a346811 100644--- a/browser_use/browser/local_browser_watchdog.py+++ b/browser_use/browser/local_browser_watchdog.py@@ -49,7 +49,10 @@ class LocalBrowserWatchdog(BaseWatchdog):f'[LocalBrowserWatchdog] Received BrowserLaunchEvent, EventBus ID: {id(self.event_bus)}, launching local browser')+ logger.debug('[LocalBrowserWatchdog] Calling _launch_browser...')process, cdp_url = await self._launch_browser()+ logger.debug(f'[LocalBrowserWatchdog] _launch_browser returned: process={process}, cdp_url={cdp_url}')+self._subprocess = processlogger.info(f'[LocalBrowserWatchdog] Browser launched successfully at {cdp_url}, PID: {process.pid}')@@ -112,40 +115,49 @@ class LocalBrowserWatchdog(BaseWatchdog):)# Get browser executable from playwright- playwright = await async_playwright().start()- try:- # Use custom executable if provided, otherwise use playwright's- if profile.executable_path:- browser_path = profile.executable_path- else:- browser_path = playwright.chromium.executable_path-- # Launch browser subprocess directly- subprocess = await asyncio.create_subprocess_exec(- browser_path,- *launch_args,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,+ # Use custom executable if provided, otherwise use playwright's+ if profile.executable_path:+ browser_path = profile.executable_path+ logger.debug(f'[LocalBrowserWatchdog] Using custom executable: {browser_path}')+ else:+ logger.debug('[LocalBrowserWatchdog] Getting browser path from playwright...')+ # Use async playwright properly with timeout+ playwright = await asyncio.wait_for(+ async_playwright().start(),+ timeout=5.0 # 5 second timeout)+ try:+ browser_path = playwright.chromium.executable_path+ logger.debug(f'[LocalBrowserWatchdog] Got browser path: {browser_path}')+ finally:+ # Always stop playwright after getting the path+ await playwright.stop()+ logger.debug('[LocalBrowserWatchdog] Playwright stopped')++ # Launch browser subprocess directly+ logger.debug(f'[LocalBrowserWatchdog] Launching browser subprocess with {len(launch_args)} args...')+ subprocess = await asyncio.create_subprocess_exec(+ browser_path,+ *launch_args,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ logger.debug(f'[LocalBrowserWatchdog] Browser subprocess launched with PID: {subprocess.pid}')- # Convert to psutil.Process- process = psutil.Process(subprocess.pid)-- # Wait for CDP to be ready and get the URL- cdp_url = await self._wait_for_cdp_url(debug_port)+ # Convert to psutil.Process+ process = psutil.Process(subprocess.pid)- # Success! Clean up any temp dirs we created but didn't use- for tmp_dir in self._temp_dirs_to_cleanup:- try:- shutil.rmtree(tmp_dir, ignore_errors=True)- except Exception:- pass+ # Wait for CDP to be ready and get the URL+ cdp_url = await self._wait_for_cdp_url(debug_port)- return process, cdp_url+ # Success! Clean up any temp dirs we created but didn't use+ for tmp_dir in self._temp_dirs_to_cleanup:+ try:+ shutil.rmtree(tmp_dir, ignore_errors=True)+ except Exception:+ pass- finally:- # Clean up playwright instance- await playwright.stop()+ return process, cdp_urlexcept Exception as e:error_str = str(e).lower()diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex c35aaf36d..c45819389 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -125,7 +125,7 @@ class BrowserSession(BaseModel):def logger(self) -> Any:"""Get instance-specific logger with session ID in the name"""if (- self._logger is None or self._browser_context is None+ self._logger is None): # keep updating the name pre-init because our id and str(self) can changeimport logging@@ -133,14 +133,19 @@ class BrowserSession(BaseModel):return self._logger@property- def cdp_client(self) -> 'CDPClient | None':- """Get the cached CDP client if it exists.+ def cdp_client(self) -> 'CDPClient':+ """Get the cached CDP client.The client is created and started in setup_browser_via_cdp_url().Returns:- The CDP client instance or None if not yet created+ The CDP client instance++ Raises:+ RuntimeError: If CDP client is not initialized yet"""+ if self._cdp_client is None:+ raise RuntimeError('CDP client not initialized - browser may not be connected yet')return self._cdp_clientdef __repr__(self) -> str:@@ -160,7 +165,7 @@ class BrowserSession(BaseModel):# Initialize and attach all watchdogs FIRST so LocalBrowserWatchdog can handle BrowserLaunchEventawait self.attach_all_watchdogs()- if self.cdp_url and self._browser_context:+ if self.cdp_url:self.event_bus.dispatch(BrowserConnectedEvent(cdp_url=self.cdp_url))return@@ -208,8 +213,6 @@ class BrowserSession(BaseModel):return# Reset state- self._browser = None- self._browser_context = Noneif self.is_local:self.cdp_url = None@@ -657,16 +660,17 @@ class BrowserSession(BaseModel):self.logger.debug(f'PDF auto-download check failed: {type(e).__name__}: {e}')self.logger.debug('π³ Starting DOM processing...')- from browser_use.browser.events import BuildDOMTreeEvent+ from browser_use.browser.events import BrowserStateRequestEventfrom browser_use.dom.views import SerializedDOMStatetry:- # Use the DOMWatchdog via event bus+ # Use the DOMWatchdog via event bus - request state with DOMresult = await asyncio.wait_for(- self.event_bus.dispatch(BuildDOMTreeEvent(previous_state=None)),+ self.event_bus.dispatch(BrowserStateRequestEvent(include_dom=True, include_screenshot=False)),timeout=45.0, # 45 second timeout for DOM processing - generous for complex pages)- content = await result.event_result()+ state_summary = await result.event_result()+ content = state_summary.dom_state if state_summary else Noneself.logger.debug('β DOM processing completed')except (TimeoutError, Exception) as e:if isinstance(e, TimeoutError):@@ -787,12 +791,6 @@ class BrowserSession(BaseModel):return clients- async def cdp_client_for_frame(self, frame_id: str) -> 'CDPClient':- """Get CDP client for a specific frame ID."""- # For now, return the main client- # In future, we'd look up which session owns this frame- return self.cdp_client-async def cdp_client_for_node(self, node: 'EnhancedDOMTreeNode') -> 'CDPClient':"""Get CDP client for a specific DOM node based on its frame."""if node.frame_id:@@ -1122,26 +1120,32 @@ class BrowserSession(BaseModel):async def remove_highlights(self) -> None:"""Remove highlights from the page using CDP."""- if self.cdp_client and self.current_target_id:- try:- # Attach to current target- session = await self.cdp_client.send.Target.attachToTarget(- params={'targetId': self.current_target_id, 'flatten': True}- )- session_id = session['sessionId']+ try:+ # Check if we have a CDP client and target+ if not self.current_target_id:+ return++ # This will raise RuntimeError if CDP client not initialized+ cdp_client = self.cdp_client++ # Attach to current target+ session = await cdp_client.send.Target.attachToTarget(+ params={'targetId': self.current_target_id, 'flatten': True}+ )+ session_id = session['sessionId']- # Remove highlights via JavaScript - matches the highlighting system from debug/highlights.py- script = """+ # Remove highlights via JavaScript - matches the highlighting system from debug/highlights.py+ script = """// Remove all browser-use highlight elementsconst highlights = document.querySelectorAll('[data-browser-use-highlight]');highlights.forEach(el => el.remove());- """- await self.cdp_client.send.Runtime.evaluate(params={'expression': script}, session_id=session_id)+ """+ await cdp_client.send.Runtime.evaluate(params={'expression': script}, session_id=session_id)- # Detach from target- await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})- except Exception as e:- self.logger.debug(f'Failed to remove highlights: {e}')+ # Detach from target+ await cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})+ except Exception as e:+ self.logger.debug(f'Failed to remove highlights: {e}')@propertydef downloaded_files(self) -> list[str]:@@ -1301,101 +1305,222 @@ class BrowserSession(BaseModel):# Use helper to navigate on the targetawait self._cdp_execute_on_target(target_to_use, commands=[('Page.enable', {}), ('Page.navigate', {'url': url})])- async def cdp_client_for_frame(self, frame_id: str) -> Any:- """Get a CDP client attached to the target containing the specified frame.-- Iterates through all targets, checks their frame trees to find which target- contains the frame with the given frame_id, then returns a CDP client- attached to that target.-- Args:- frame_id: The frame ID to search for-+ async def get_all_frames(self) -> tuple[dict[str, dict], dict[str, str]]:+ """Get a complete frame hierarchy from all browser targets.+Returns:- CDP client attached to the target containing the frame-- Raises:- ValueError: If the frame is not found in any target+ Tuple of (all_frames, target_sessions) where:+ - all_frames: dict mapping frame_id -> frame info dict with all metadata+ - target_sessions: dict mapping target_id -> session_id for active sessions"""+ all_frames = {} # frame_id -> FrameInfo dict+ target_sessions = {} # target_id -> session_id (keep sessions alive during collection)+# Get all targetstargets = await self.cdp_client.send.Target.getTargets()all_targets = targets.get('targetInfos', [])-- # Check each target's frame tree (page and iframe targets)++ # First pass: collect frame trees from ALL targetsfor target in all_targets:target_id = target.get('targetId')- target_type = target.get('type')- # Skip non-page/iframe targets as they don't have frames- if not target_id or target_type not in ['page', 'iframe']:+ if not target_id:continue-- # Attach to target to get frame tree- session = await self.cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})++ # Attach to target+ session = await self.cdp_client.send.Target.attachToTarget(+ params={'targetId': target_id, 'flatten': True}+ )session_id = session['sessionId']-+ target_sessions[target_id] = session_id+try:- if target_type == 'page':- # For page targets, check the frame tree- # Enable Page domain first (only works for page targets)+ # Set auto-attach to get related targets+ await self.cdp_client.send.Target.setAutoAttach(+ params={+ 'autoAttach': True,+ 'waitForDebuggerOnStart': False,+ 'flatten': True+ },+ session_id=session_id+ )++ # Try to get frame tree (not all target types support this)+ try:await self.cdp_client.send.Page.enable(session_id=session_id)-- # Get the frame tree for this targetframe_tree_result = await self.cdp_client.send.Page.getFrameTree(session_id=session_id)-- # Check if frame_id exists in this target's frame tree- def frame_exists_in_tree(frame_node: dict) -> bool:- """Recursively check if frame_id exists in the frame tree."""- # Check current frame- if frame_node.get('frame', {}).get('id') == frame_id:- return True-- # Check child frames recursively- child_frames = frame_node.get('childFrames', [])- for child in child_frames:- if frame_exists_in_tree(child):- return True-- return False-- # Check if the frame exists in this target's tree- if frame_exists_in_tree(frame_tree_result.get('frameTree', {})):- # Frame found! Keep the session attached and return a client for it- # Note: We're returning the cdp_client with the session already attached- # The caller is responsible for detaching when done- return self.cdp_client, session_id, target_id++ # Process the frame tree recursively+ def process_frame_tree(node, parent_frame_id=None):+ """Recursively process frame tree and add to all_frames."""+ frame = node.get('frame', {})+ current_frame_id = frame.get('id')- elif target_type == 'iframe':- # For iframe targets (OOPIFs), the target itself IS the frame- # We need to check if this iframe target's frame ID matches what we're looking for+ if current_frame_id:+ # Create frame info with all CDP response data plus our additions+ frame_info = {+ **frame, # Include all original frame data+ 'frameTargetId': target_id, # Target that can access this frame+ 'parentFrameId': parent_frame_id, # Parent frame ID if any+ 'childFrameIds': [], # Will be populated below+ 'isCrossOrigin': False, # Will be determined based on context+ }++ # Check if frame is cross-origin based on crossOriginIsolatedContextType+ cross_origin_type = frame.get('crossOriginIsolatedContextType')+ if cross_origin_type and cross_origin_type != 'NotIsolated':+ frame_info['isCrossOrigin'] = True++ # For iframe targets, the frame itself is likely cross-origin+ if target.get('type') == 'iframe':+ frame_info['isCrossOrigin'] = True++ # Add child frame IDs (note: OOPIFs won't appear here)+ child_frames = node.get('childFrames', [])+ for child in child_frames:+ child_frame = child.get('frame', {})+ child_frame_id = child_frame.get('id')+ if child_frame_id:+ frame_info['childFrameIds'].append(child_frame_id)++ # Store or merge frame info+ if current_frame_id in all_frames:+ # Frame already seen from another target, merge info+ existing = all_frames[current_frame_id]+ # If this is an iframe target, it has direct access to the frame+ if target.get('type') == 'iframe':+ existing['frameTargetId'] = target_id+ existing['isCrossOrigin'] = True+ else:+ all_frames[current_frame_id] = frame_info++ # Process child frames recursively+ for child in child_frames:+ process_frame_tree(child, current_frame_id)++ # Process the entire frame tree+ process_frame_tree(frame_tree_result.get('frameTree', {}))++ except Exception:+ # Target doesn't support Page domain or has no frames+ pass++ except Exception:+ # Error processing this target+ pass++ # Second pass: populate backend node IDs and parent target IDs+ await self._populate_frame_metadata(all_frames, target_sessions)++ return all_frames, target_sessions++ async def _populate_frame_metadata(self, all_frames: dict[str, dict], target_sessions: dict[str, str]) -> None:+ """Populate additional frame metadata like backend node IDs and parent target IDs.++ Args:+ all_frames: Frame hierarchy dict to populate+ target_sessions: Active target sessions+ """+ for frame_id_iter, frame_info in all_frames.items():+ parent_frame_id = frame_info.get('parentFrameId')++ if parent_frame_id and parent_frame_id in all_frames:+ parent_frame_info = all_frames[parent_frame_id]+ parent_target_id = parent_frame_info.get('frameTargetId')++ # Store parent target ID+ frame_info['parentTargetId'] = parent_target_id++ # Try to get backend node ID from parent context+ if parent_target_id in target_sessions:+ parent_session_id = target_sessions[parent_target_id]try:- # Enable Page domain to get frame info- await self.cdp_client.send.Page.enable(session_id=session_id)-- # Get the frame tree for this iframe target- frame_tree_result = await self.cdp_client.send.Page.getFrameTree(session_id=session_id)+ # Enable DOM domain+ await self.cdp_client.send.DOM.enable(session_id=parent_session_id)- # For an iframe target, the root frame IS the iframe itself- iframe_frame_id = frame_tree_result.get('frameTree', {}).get('frame', {}).get('id')+ # Get frame owner info to find backend node ID+ frame_owner = await self.cdp_client.send.DOM.getFrameOwner(+ params={'frameId': frame_id_iter},+ session_id=parent_session_id+ )- if iframe_frame_id == frame_id:- # This is the iframe we're looking for!- # Don't detach - caller is responsible for cleanup- return self.cdp_client, session_id, target_id+ if frame_owner:+ frame_info['backendNodeId'] = frame_owner.get('backendNodeId')+ frame_info['nodeId'] = frame_owner.get('nodeId')except Exception:- # This iframe target doesn't match+ # Frame owner not available (likely cross-origin)pass-- # If we didn't find the frame in this target, detach before trying next one- await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})-- except Exception as e:- # On error, make sure to detach- await self.cdp_client.send.Target.detachFromTarget(params={'sessionId': session_id})- raise- # Frame not found in any target+ async def find_frame_target(self, frame_id: str, all_frames: dict[str, dict] | None = None) -> dict | None:+ """Find the frame info for a specific frame ID.++ Args:+ frame_id: The frame ID to search for+ all_frames: Optional pre-built frame hierarchy. If None, will call get_all_frames()++ Returns:+ Frame info dict if found, None otherwise+ """+ if all_frames is None:+ all_frames, _ = await self.get_all_frames()++ return all_frames.get(frame_id)++ async def cleanup_target_sessions(self, target_sessions: dict[str, str], keep_target_id: str | None = None) -> None:+ """Clean up CDP sessions by detaching from targets.++ Args:+ target_sessions: Dict of target_id -> session_id to clean up+ keep_target_id: Optional target ID to keep attached (won't detach this one)+ """+ for target_id, session_id in target_sessions.items():+ if target_id != keep_target_id:+ try:+ await self.cdp_client.send.Target.detachFromTarget(+ params={'sessionId': session_id}+ )+ except Exception:+ pass++ async def cdp_client_for_frame(self, frame_id: str) -> Any:+ """Get a CDP client attached to the target containing the specified frame.++ Builds a unified frame hierarchy from all targets to find the correct target+ for any frame, including OOPIFs (Out-of-Process iframes).++ Args:+ frame_id: The frame ID to search for++ Returns:+ Tuple of (cdp_client, session_id, target_id) for the target containing the frame++ Raises:+ ValueError: If the frame is not found in any target+ """+ # Get complete frame hierarchy+ all_frames, target_sessions = await self.get_all_frames()++ # Find the requested frame+ frame_info = await self.find_frame_target(frame_id, all_frames)++ if frame_info:+ target_id = frame_info.get('frameTargetId')++ if target_id in target_sessions:+ # Use existing session+ session_id = target_sessions[target_id]++ # Clean up other sessions before returning+ await self.cleanup_target_sessions(target_sessions, keep_target_id=target_id)++ # Return the client with session attached (caller must detach)+ return self.cdp_client, session_id, target_id++ # Clean up all sessions before raising error+ await self.cleanup_target_sessions(target_sessions)++ # Frame not foundraise ValueError(f"Frame with ID '{frame_id}' not found in any target")async def cdp_client_for_target(self, target_id: str) -> Any:diff --git a/browser_use/browser/storage_state_watchdog.py b/browser_use/browser/storage_state_watchdog.pyindex fbd869a70..a5a822d97 100644--- a/browser_use/browser/storage_state_watchdog.py+++ b/browser_use/browser/storage_state_watchdog.py@@ -18,7 +18,6 @@ from browser_use.browser.events import (StorageStateSavedEvent,)from browser_use.browser.watchdog_base import BaseWatchdog-from browser_use.utils import loggerclass StorageStateWatchdog(BaseWatchdog):@@ -47,7 +46,7 @@ class StorageStateWatchdog(BaseWatchdog):async def on_BrowserConnectedEvent(self, event: BrowserConnectedEvent) -> None:"""Start monitoring when browser starts."""- logger.info('[StorageStateWatchdog] πͺ Initializing auth/cookies sync <-> with storage_state.json file')+ self.logger.info('[StorageStateWatchdog] πͺ Initializing auth/cookies sync <-> with storage_state.json file')# Start monitoringawait self._start_monitoring()@@ -57,18 +56,18 @@ class StorageStateWatchdog(BaseWatchdog):async def on_BrowserStopEvent(self, event: BrowserStopEvent) -> None:"""Stop monitoring and save state when browser stop is requested."""- logger.info('[StorageStateWatchdog] Browser stop requested, saving final storage_state.json')+ self.logger.info('[StorageStateWatchdog] Browser stop requested, saving final storage_state.json')# Save storage state before stopping and wait for completion- # logger.info('[StorageStateWatchdog] Dispatching SaveStorageStateEvent...')+ # self.logger.info('[StorageStateWatchdog] Dispatching SaveStorageStateEvent...')save_event = self.event_bus.dispatch(SaveStorageStateEvent())- # logger.info('[StorageStateWatchdog] Waiting for save event to complete...')+ # self.logger.info('[StorageStateWatchdog] Waiting for save event to complete...')await save_event- # logger.info('[StorageStateWatchdog] Save event completed, stopping monitoring...')+ # self.logger.info('[StorageStateWatchdog] Save event completed, stopping monitoring...')# Stop monitoringawait self._stop_monitoring()- # logger.info('[StorageStateWatchdog] Browser stop handling complete')+ # self.logger.info('[StorageStateWatchdog] Browser stop handling complete')# No cleanup needed - browser context is managed by sessionasync def on_SaveStorageStateEvent(self, event: SaveStorageStateEvent) -> None:@@ -101,7 +100,7 @@ class StorageStateWatchdog(BaseWatchdog):returnself._monitoring_task = asyncio.create_task(self._monitor_storage_changes())- # logger.info('[StorageStateWatchdog] Started storage monitoring task')+ # self.logger.info('[StorageStateWatchdog] Started storage monitoring task')# Set up monitoring for existing targetsif self.browser_session.cdp_client:@@ -117,7 +116,7 @@ class StorageStateWatchdog(BaseWatchdog):await self._monitoring_taskexcept asyncio.CancelledError:pass- # logger.debug('[StorageStateWatchdog] Stopped storage monitoring task')+ # self.logger.debug('[StorageStateWatchdog] Stopped storage monitoring task')def _setup_target_monitoring(self, target_id: str) -> None:"""Set up storage change monitoring for a target.@@ -126,7 +125,7 @@ class StorageStateWatchdog(BaseWatchdog):via Network.responseReceivedExtraInfo events."""# For now, rely on periodic monitoring- logger.debug(f'[StorageStateWatchdog] Target {target_id} will be monitored via periodic checks')+ self.logger.debug(f'[StorageStateWatchdog] Target {target_id} will be monitored via periodic checks')async def _check_for_cookie_changes_cdp(self, event: dict) -> None:"""Check if a CDP network event indicates cookie changes.@@ -243,19 +242,19 @@ class StorageStateWatchdog(BaseWatchdog):))- logger.info(+ self.logger.info(f'[StorageStateWatchdog] Saved storage state to {json_path} 'f'({len(merged_state.get("cookies", []))} cookies, 'f'{len(merged_state.get("origins", []))} origins)')except Exception as e:- logger.error(f'[StorageStateWatchdog] Failed to save storage state: {e}')+ self.logger.error(f'[StorageStateWatchdog] Failed to save storage state: {e}')async def _load_storage_state(self, path: str | None = None) -> None:"""Load browser storage state from file."""if not self.browser_session.cdp_client:- logger.warning('[StorageStateWatchdog] No CDP client available for loading')+ self.logger.warning('[StorageStateWatchdog] No CDP client available for loading')returnload_path = path or self.browser_session.browser_profile.storage_state@@ -273,7 +272,7 @@ class StorageStateWatchdog(BaseWatchdog):if 'cookies' in storage and storage['cookies']:await self.browser_session._cdp_set_cookies(storage['cookies'])self._last_cookie_state = storage['cookies'].copy()- logger.info(f'[StorageStateWatchdog] Added {len(storage["cookies"])} cookies from storage state')+ self.logger.info(f'[StorageStateWatchdog] Added {len(storage["cookies"])} cookies from storage state')# Apply origins (localStorage/sessionStorage) if presentif 'origins' in storage and storage['origins']:@@ -290,7 +289,7 @@ class StorageStateWatchdog(BaseWatchdog):window.sessionStorage.setItem({json.dumps(item['name'])}, {json.dumps(item['value'])});"""await self.browser_session._cdp_add_init_script(script)- logger.info(f'[StorageStateWatchdog] Applied localStorage/sessionStorage from {len(storage["origins"])} origins')+ self.logger.info(f'[StorageStateWatchdog] Applied localStorage/sessionStorage from {len(storage["origins"])} origins')self.event_bus.dispatch(StorageStateLoadedEvent(@@ -300,10 +299,10 @@ class StorageStateWatchdog(BaseWatchdog):))- logger.info(f'[StorageStateWatchdog] Loaded storage state from: {load_path}')+ self.logger.info(f'[StorageStateWatchdog] Loaded storage state from: {load_path}')except Exception as e:- logger.error(f'[StorageStateWatchdog] Failed to load storage state: {e}')+ self.logger.error(f'[StorageStateWatchdog] Failed to load storage state: {e}')@staticmethoddef _merge_storage_states(existing: dict[str, Any], new: dict[str, Any]) -> dict[str, Any]:@@ -337,21 +336,21 @@ class StorageStateWatchdog(BaseWatchdog):try:return await self.browser_session._cdp_get_cookies()except Exception as e:- logger.error(f'[StorageStateWatchdog] Failed to get cookies: {e}')+ self.logger.error(f'[StorageStateWatchdog] Failed to get cookies: {e}')return []async def add_cookies(self, cookies: list[dict[str, Any]]) -> None:"""Add cookies using CDP."""if not self.browser_session.cdp_client:- logger.warning('[StorageStateWatchdog] No CDP client available for adding cookies')+ self.logger.warning('[StorageStateWatchdog] No CDP client available for adding cookies')returntry:# Set cookies using CDPawait self.browser_session._cdp_set_cookies(cookies)- logger.info(f'[StorageStateWatchdog] Added {len(cookies)} cookies')+ self.logger.info(f'[StorageStateWatchdog] Added {len(cookies)} cookies')except Exception as e:- logger.error(f'[StorageStateWatchdog] Failed to add cookies: {e}')+ self.logger.error(f'[StorageStateWatchdog] Failed to add cookies: {e}')# Fix Pydantic circular dependency - this will be called from session.py after BrowserSession is defineddiff --git a/browser_use/browser/watchdog_base.py b/browser_use/browser/watchdog_base.pyindex 379ad3d61..dc5623dda 100644--- a/browser_use/browser/watchdog_base.py+++ b/browser_use/browser/watchdog_base.py@@ -6,8 +6,6 @@ from typing import TYPE_CHECKING, ClassVarfrom bubus import BaseEvent, EventBusfrom pydantic import BaseModel, ConfigDict-from browser_use.utils import logger-if TYPE_CHECKING:from browser_use.browser.session import BrowserSession@@ -35,6 +33,11 @@ class BaseWatchdog(BaseModel):event_bus: EventBusbrowser_session: 'BrowserSession'+ @property+ def logger(self):+ """Get the logger from the browser session."""+ return self.browser_session.logger+async def attach_to_session(self) -> None:"""Attach watchdog to its browser session and start monitoring.@@ -73,7 +76,7 @@ class BaseWatchdog(BaseModel):# Capture handler by value to avoid closure issuesdef make_unique_handler(actual_handler):async def unique_handler(event):- logger.debug(+ self.logger.debug(f'[{self.__class__.__name__}] calling {actual_handler.__name__}({event.__class__.__name__})')return await actual_handler(event)@@ -100,7 +103,7 @@ class BaseWatchdog(BaseModel):missing_handlers = set(self.LISTENS_TO) - registered_eventsif missing_handlers:missing_names = [e.__name__ for e in missing_handlers]- logger.warning(+ self.logger.warning(f'[{self.__class__.__name__}] LISTENS_TO declares {missing_names} 'f'but no handlers found (missing on_{"_, on_".join(missing_names)} methods)')@@ -121,7 +124,7 @@ class BaseWatchdog(BaseModel):task = getattr(self, attr_name)if hasattr(task, 'cancel') and callable(task.cancel) and not task.done():task.cancel()- logger.debug(f'[{self.__class__.__name__}] Cancelled {attr_name} during cleanup')+ self.logger.debug(f'[{self.__class__.__name__}] Cancelled {attr_name} during cleanup')except Exception:pass # Ignore errors during cleanupdiff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex ca518e235..3bc17bdec 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -59,23 +59,44 @@ class DomService:# Cleanup any attached sessionsawait self._cleanup_sessions()- async def _get_targets_for_current_page(self) -> CurrentPageTargets:- """Get the target for the current page."""+ async def _get_targets_for_page(self, target_id: str | None = None) -> CurrentPageTargets:+ """Get the target info for a specific page.++ Args:+ target_id: The target ID to get info for. If None, uses current_target_id.+ """targets = await self.browser_session.cdp_client.send.Target.getTargets()- # Use the current_target_id directly- current_target_id = self.browser_session.current_target_id- if not current_target_id:- raise ValueError('No current target ID set in browser session')+ # Use provided target_id or fall back to current_target_id+ if target_id is None:+ target_id = self.browser_session.current_target_id+ if not target_id:+ raise ValueError('No current target ID set in browser session')# Find main page target by ID- main_target = next((t for t in targets['targetInfos'] if t['targetId'] == current_target_id), None)+ main_target = next((t for t in targets['targetInfos'] if t['targetId'] == target_id), None)if not main_target:- raise ValueError(f'No target found for current target ID: {current_target_id}')-- # Separate iframe targets for attachment- iframe_targets = [t for t in targets['targetInfos'] if t['type'] == 'iframe']+ raise ValueError(f'No target found for target ID: {target_id}')++ # Get all frames using the new method to find iframe targets for this page+ all_frames, _ = await self.browser_session.get_all_frames()++ # Find iframe targets that are children of this target+ iframe_targets = []+ for frame_info in all_frames.values():+ # Check if this frame is a cross-origin iframe with its own target+ if frame_info.get('isCrossOrigin') and frame_info.get('frameTargetId'):+ # Check if this frame belongs to our target+ parent_target = frame_info.get('parentTargetId', frame_info.get('frameTargetId'))+ if parent_target == target_id:+ # Find the target info for this iframe+ iframe_target = next(+ (t for t in targets['targetInfos'] if t['targetId'] == frame_info['frameTargetId']),+ None+ )+ if iframe_target:+ iframe_targets.append(iframe_target)return CurrentPageTargets(page_session=main_target,@@ -86,7 +107,6 @@ class DomService:"""This function is cached, so go crazy"""target_id = str(target['targetId'])- print(f'DomService._attach_target: Attaching to target {target_id}, type={target.get("type")}')# if target_id in self.target_to_session_id_cache:# return self.target_to_session_id_cache[target_id]@@ -96,17 +116,13 @@ class DomService:params={'targetId': target_id, 'flatten': True})session_id = session['sessionId']- print(f'DomService: Successfully attached, got session_id={session_id}')except Exception as e:- print(f'DomService ERROR: Failed to attach to target {target_id}: {e}')raise# Track this session for cleanupself._attached_sessions.add(session_id)- print(f'DomService: Enabling domains on session {session_id}...')await self._enable_all_domains_on_session(session_id)- print(f'DomService: Domains enabled on session {session_id}')return session_id@@ -124,11 +140,20 @@ class DomService:if session_id in self.session_id_domains_enabled_cache:return+ # Set auto-attach with proper filter for iframe targets+ # This will automatically attach to immediate child frames+ # IMPORTANT: This is NOT recursive - we need to call setAutoAttach+ # on each newly attached frame to get its childrenawait self.browser_session.cdp_client.send.Target.setAutoAttach(params={'autoAttach': True,'waitForDebuggerOnStart': False,'flatten': True,+ # Include filter to ensure iframe targets are attached+ 'filter': [+ {'type': 'page', 'exclude': False},+ {'type': 'iframe', 'exclude': False}+ ]},session_id=session_id,)@@ -306,19 +331,13 @@ class DomService:if not self.browser_session.cdp_url:raise ValueError('CDP URL is not set')- print(f'DomService._get_all_trees_for_session_id: Starting with session_id={session_id}')-# Wait for the page to be ready firsttry:- print('DomService: Checking page ready state...')ready_state = await self.browser_session.cdp_client.send.Runtime.evaluate(params={'expression': 'document.readyState'}, session_id=session_id)- print(f'DomService: Page ready state: {ready_state}')except Exception as e:- print(f'Warning: Could not check page ready state: {e}')-- print('DomService: Creating CDP requests...')+ pass # Page might not be ready yetsnapshot_request = self.browser_session.cdp_client.send.DOMSnapshot.captureSnapshot(params={'computedStyles': REQUIRED_COMPUTED_STYLES,@@ -339,27 +358,19 @@ class DomService:device_pixel_ratio_request = self._get_viewport_ratio(session_id)start = time.time()- # Use wait_for with timeout to debug which call is hanging+ # Gather all CDP requests with timeouttry:- print('DomService: Gathering all CDP requests...')snapshot, dom_tree, ax_tree, device_pixel_ratio = await asyncio.wait_for(asyncio.gather(snapshot_request, dom_tree_request, ax_tree_request, device_pixel_ratio_request), timeout=10.0)- print('DomService: All CDP requests completed successfully')except TimeoutError:- print('ERROR: CDP calls timed out in _get_all_trees_for_session_id')# Try to get them individually to see which one hangs- print('Trying snapshot...')snapshot = await asyncio.wait_for(snapshot_request, timeout=2.0)- print('Trying dom_tree...')dom_tree = await asyncio.wait_for(dom_tree_request, timeout=2.0)- print('Trying ax_tree...')ax_tree = await asyncio.wait_for(ax_tree_request, timeout=2.0)- print('Trying device_pixel_ratio...')device_pixel_ratio = await asyncio.wait_for(device_pixel_ratio_request, timeout=2.0)end = time.time()cdp_timing = {'cdp_calls_total': end - start}- print(f'Time taken to get dom tree: {end - start} seconds')return TargetAllTrees(snapshot=snapshot,@@ -371,12 +382,23 @@ class DomService:async def get_dom_tree(self,- target: TargetInfo,+ target_id: str | None = None,initial_html_frames: list[EnhancedDOMTreeNode] | None = None,initial_total_frame_offset: DOMRect | None = None,) -> EnhancedDOMTreeNode:+ """Get the DOM tree for a specific target.++ Args:+ target_id: Optional target ID. If None, uses current target.+ initial_html_frames: List of HTML frame nodes encountered so far+ initial_total_frame_offset: Accumulated coordinate offset+ """+ # Get target info+ page_session_info = await self._get_targets_for_page(target_id)+ target = page_session_info.page_session+ actual_target_id = target['targetId'] # Store the actual target ID being used+# Get viewport dimensions first for visibility calculation-session_id = await self._attach_target_activate_domains_get_session_id(target)trees = await self._get_all_trees_for_session_id(session_id)@@ -463,7 +485,7 @@ class DomService:attributes=attributes or {},is_scrollable=node.get('isScrollable', None),frame_id=node.get('frameId', None),- target_id=target['targetId'],+ target_id=actual_target_id,content_document=None,shadow_root_type=shadow_root_type,shadow_roots=None,@@ -533,15 +555,26 @@ class DomService:# TODO: hacky way to disable cross origin iframes for nowENABLE_CROSS_ORIGIN_IFRAMES and node['nodeName'].upper() == 'IFRAME' and node.get('contentDocument', None) is None): # None meaning there is no content- targets = await self._get_targets_for_current_page()- iframe_document_target = next(- (iframe for iframe in targets.iframe_sessions if iframe.get('targetId') == node.get('frameId', None)), None- )+ # Use get_all_frames to find the iframe's target+ frame_id = node.get('frameId', None)+ if frame_id:+ all_frames, _ = await self.browser_session.get_all_frames()+ frame_info = all_frames.get(frame_id)+ iframe_document_target = None+ if frame_info and frame_info.get('frameTargetId'):+ # Get the target info for this iframe+ targets = await self.browser_session.cdp_client.send.Target.getTargets()+ iframe_document_target = next(+ (t for t in targets['targetInfos'] if t['targetId'] == frame_info['frameTargetId']),+ None+ )+ else:+ iframe_document_target = None# if target actually exists in one of the frames, just recursively build the dom tree for itif iframe_document_target:print(f'π Getting content document for iframe {node.get("frameId", None)}')content_document = await self.get_dom_tree(- iframe_document_target,+ target_id=iframe_document_target.get('targetId'),# TODO: experiment with this values -> not sure whether the whole cross origin iframe should be ALWAYS included as soon as some part of it is visible or not.# Current config: if the cross origin iframe is AT ALL visible, then just include everything inside of it!# initial_html_frames=updated_html_frames,@@ -567,13 +600,8 @@ class DomService:"""try:- print('DomService: Getting targets for current page...')- page_session_info = await self._get_targets_for_current_page()- print(f'DomService: Got page session info, target_id={page_session_info.page_session.get("targetId")}')-- print('DomService: Getting DOM tree...')- enhanced_dom_tree = await self.get_dom_tree(page_session_info.page_session)- print('DomService: Got enhanced DOM tree')+ # Use current target (None means use current)+ enhanced_dom_tree = await self.get_dom_tree(target_id=None)start = time.time()serialized_dom_state, serializer_timing = DOMTreeSerializer(@@ -582,7 +610,6 @@ class DomService:end = time.time()serialize_total_timing = {'serialize_dom_tree_total': end - start}- print(f'Time taken to serialize dom tree: {end - start} seconds')# Combine all timing infoall_timing = {**serializer_timing, **serialize_total_timing}diff --git a/pyproject.toml b/pyproject.tomlindex 9d5d1ffb8..f4689d16b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -41,7 +41,7 @@ dependencies = ["google-auth-oauthlib>=1.2.2","mcp>=1.10.1","pypdf>=5.7.0",- "cdp-use>=1.3.2",+ "cdp-use>=1.3.4","markdown-pdf==1.5",]# google-api-core: only used for Google LLM APIs