Skip to content

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

add cdp_client_for_target and cdp_client_for_frame helpers

Nick Sweeting3e71e74bc7d1
diff --git a/browser_use/browser/dom_watchdog.py b/browser_use/browser/dom_watchdog.py
index a9dec544a..a260c9ec2 100644
--- a/browser_use/browser/dom_watchdog.py
+++ b/browser_use/browser/dom_watchdog.py
@@ -240,9 +240,11 @@ class DOMWatchdog(BaseWatchdog):
# Get serialized DOM tree using the service
start = time.time()
+ print(f"DOMWatchdog: About to call get_serialized_dom_tree with dom_service={self._dom_service}")
self.current_dom_state, self.enhanced_dom_tree, timing_info = await self._dom_service.get_serialized_dom_tree(
previous_cached_state=event.previous_state
)
+ print(f"DOMWatchdog: Returned from get_serialized_dom_tree")
end = time.time()
logger.debug(f'Time taken to get DOM tree: {end - start} seconds')
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 6515ffa95..330335d3c 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -1319,6 +1319,95 @@ class BrowserSession(BaseModel):
('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
+
+ Returns:
+ CDP client attached to the target containing the frame
+
+ Raises:
+ ValueError: If the frame is not found in any target
+ """
+ # Get all targets
+ targets = await self.cdp_client.send.Target.getTargets()
+ all_targets = targets.get('targetInfos', [])
+
+ # Check each target's frame tree
+ for target in all_targets:
+ target_id = target.get('targetId')
+ 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}
+ )
+ session_id = session['sessionId']
+
+ try:
+ # Get the frame tree for this target
+ frame_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
+
+ finally:
+ # Detach from target if frame not found
+ await self.cdp_client.send.Target.detachFromTarget(
+ params={'sessionId': session_id}
+ )
+
+ # Frame not found in any target
+ raise ValueError(f"Frame with ID '{frame_id}' not found in any target")
+
+ async def cdp_client_for_target(self, target_id: str) -> Any:
+ """Get a CDP client attached to a specific target.
+
+ This is a simpler helper that just attaches to a specific target ID.
+
+ Args:
+ target_id: The target ID to attach to
+
+ Returns:
+ Tuple of (cdp_client, session_id) for the attached target
+ """
+ session = await self.cdp_client.send.Target.attachToTarget(
+ params={'targetId': target_id, 'flatten': True}
+ )
+ session_id = session['sessionId']
+
+ # Return the client and session_id
+ # Caller is responsible for detaching when done
+ return self.cdp_client, session_id
# Import uuid7str for ID generation
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index 5effab9df..6a854c0ce 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -61,21 +61,33 @@ class DomService:
async def _get_targets_for_current_page(self) -> CurrentPageTargets:
"""Get the target for the current page."""
+ print(f"DomService._get_targets_for_current_page: Getting targets...")
targets = await self.browser_session.cdp_client.send.Target.getTargets()
+ print(f"DomService: Found {len(targets.get('targetInfos', []))} targets")
# 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')
+
+ print(f"DomService: Looking for target with ID: {current_target_id}")
# Find main page target by ID
main_target = next((t for t in targets['targetInfos'] if t['targetId'] == current_target_id), None)
if not main_target:
+ # Debug: print all available targets
+ print(f"DomService ERROR: No target found for current target ID: {current_target_id}")
+ print(f"Available targets:")
+ for t in targets['targetInfos']:
+ print(f" - {t['targetId']}: type={t['type']}, url={t.get('url', 'none')}")
raise ValueError(f'No target found for current target ID: {current_target_id}')
+
+ print(f"DomService: Found main target: type={main_target['type']}, url={main_target.get('url', 'none')}")
# Separate iframe targets for attachment
iframe_targets = [t for t in targets['targetInfos'] if t['type'] == 'iframe']
+ print(f"DomService: Found {len(iframe_targets)} iframe targets")
return CurrentPageTargets(
page_session=main_target,
@@ -86,19 +98,27 @@ 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]
- session = await self.browser_session.cdp_client.send.Target.attachToTarget(
- params={'targetId': target_id, 'flatten': True}
- )
- session_id = session['sessionId']
+ try:
+ session = await self.browser_session.cdp_client.send.Target.attachToTarget(
+ 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 cleanup
self._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
@@ -300,15 +320,20 @@ 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 first
try:
- await self.browser_session.cdp_client.send.Runtime.evaluate(
+ print(f"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(f"DomService: Creating CDP requests...")
snapshot_request = self.browser_session.cdp_client.send.DOMSnapshot.captureSnapshot(
params={
'computedStyles': REQUIRED_COMPUTED_STYLES,
@@ -331,12 +356,14 @@ class DomService:
start = time.time()
# Use wait_for with timeout to debug which call is hanging
try:
+ print(f"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(f"DomService: All CDP requests completed successfully")
except asyncio.TimeoutError:
print("ERROR: CDP calls timed out in _get_all_trees_for_session_id")
# Try to get them individually to see which one hangs