Skip to content

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

cross origin iframe support

Gregor Žunič163ea5def63b
diff --git a/browser_use/dom/debug/highlights.py b/browser_use/dom/debug/highlights.py
index 4e977b06a..25b66b4ee 100644
--- a/browser_use/dom/debug/highlights.py
+++ b/browser_use/dom/debug/highlights.py
@@ -54,7 +54,8 @@ async def remove_highlighting_script(dom_service: DomService) -> None:
try:
# Get CDP client and session ID
cdp_client = await dom_service._get_cdp_client()
- session_id = await dom_service._get_current_page_session_id()
+ targets = await dom_service._get_targets_for_current_page()
+ session_id = await dom_service._attach_target_activate_domains_get_session_id(targets.page_session)
print('🧹 Removing browser-use highlighting elements')
@@ -89,7 +90,8 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen
# Get CDP client and session ID
cdp_client = await dom_service._get_cdp_client()
- session_id = await dom_service._get_current_page_session_id()
+ targets = await dom_service._get_targets_for_current_page()
+ session_id = await dom_service._attach_target_activate_domains_get_session_id(targets.page_session)
print(f'📍 Creating CSP-safe highlighting for {len(converted_elements)} elements')
diff --git a/browser_use/dom/playground/extraction.py b/browser_use/dom/playground/extraction.py
index b718314cb..9b2f51748 100644
--- a/browser_use/dom/playground/extraction.py
+++ b/browser_use/dom/playground/extraction.py
@@ -33,7 +33,7 @@ async def test_focus_vs_all_elements():
# 10 Sample websites with various interactive elements
sample_websites = [
- 'https://v0-website-with-clickable-elements.vercel.app/nested-iframe',
+ 'https://v0-website-with-clickable-elements.vercel.app/cross-origin',
'https://www.google.com/travel/flights',
'https://www.amazon.com/s?k=laptop',
'https://github.com/trending',
diff --git a/browser_use/dom/serializer/serializer.py b/browser_use/dom/serializer/serializer.py
index 2b34ff2df..cf9859bcf 100644
--- a/browser_use/dom/serializer/serializer.py
+++ b/browser_use/dom/serializer/serializer.py
@@ -219,8 +219,12 @@ class DOMTreeSerializer:
formatted_text.append(child_text)
return '\n'.join(formatted_text)
- # Add element with interactive_index if clickable or scrollable
- if node.interactive_index is not None or node.original_node.is_scrollable:
+ # Add element with interactive_index if clickable, scrollable, or iframe
+ if (
+ node.interactive_index is not None
+ or node.original_node.is_scrollable
+ or node.original_node.tag_name.upper() == 'IFRAME'
+ ):
next_depth += 1
# Build attributes string
@@ -235,6 +239,9 @@ class DOMTreeSerializer:
new_prefix = '*' if node.is_new else ''
scroll_prefix = '|SCROLL+' if node.original_node.is_scrollable else '['
line = f'{depth_str}{new_prefix}{scroll_prefix}{node.interactive_index}]<{node.original_node.tag_name}'
+ elif node.original_node.tag_name.upper() == 'IFRAME':
+ # Iframe element (not interactive)
+ line = f'{depth_str}|IFRAME|<{node.original_node.tag_name}'
else:
line = f'{depth_str}<{node.original_node.tag_name}'
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index e1783ff5e..399aba7b7 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -6,9 +6,8 @@ import httpx
from cdp_use import CDPClient
from cdp_use.cdp.accessibility.commands import GetFullAXTreeReturns
from cdp_use.cdp.accessibility.types import AXNode
-from cdp_use.cdp.dom.commands import GetDocumentReturns
from cdp_use.cdp.dom.types import Node
-from cdp_use.cdp.domsnapshot.commands import CaptureSnapshotReturns
+from cdp_use.cdp.target.types import TargetInfo
from browser_use.dom.enhanced_snapshot import (
REQUIRED_COMPUTED_STYLES,
@@ -16,12 +15,14 @@ from browser_use.dom.enhanced_snapshot import (
)
from browser_use.dom.serializer.serializer import DOMTreeSerializer
from browser_use.dom.views import (
+ CurrentPageTargets,
DOMRect,
EnhancedAXNode,
EnhancedAXProperty,
EnhancedDOMTreeNode,
NodeType,
SerializedDOMState,
+ TargetAllTrees,
)
if TYPE_CHECKING:
@@ -45,6 +46,8 @@ class DomService:
self.cdp_client: CDPClient | None = None
# self.playwright_page_to_session_id_store: dict[str, str] = {}
+ self.target_to_session_id_cache: dict[str, str] = {}
+
async def _get_cdp_client(self) -> CDPClient:
if not self.browser.cdp_url:
raise ValueError('CDP URL is not set')
@@ -78,7 +81,7 @@ class DomService:
await self.cdp_client.stop()
self.cdp_client = None
- async def _get_current_page_session_id(self) -> str:
+ async def _get_targets_for_current_page(self) -> CurrentPageTargets:
"""Get the target ID for a playwright page.
TODO: this is a REALLY hacky way -> if multiple same urls are open then this will break
@@ -90,28 +93,54 @@ class DomService:
# return self.page_to_session_id_store[page_guid]
cdp_client = await self._get_cdp_client()
-
targets = await cdp_client.send.Target.getTargets()
- for target in targets['targetInfos']:
- if target['type'] == 'page' and target['url'] == self.page.url:
- # cache the session id for this playwright page
- # self.playwright_page_to_session_id_store[page_guid] = target['targetId']
- session = await cdp_client.send.Target.attachToTarget(params={'targetId': target['targetId'], 'flatten': True})
- session_id = session['sessionId']
+ # Find main page target
+ main_target = next((t for t in targets['targetInfos'] if t['type'] == 'page' and t['url'] == self.page.url), None)
- await cdp_client.send.Target.setAutoAttach(
- params={'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True}
- )
+ if not main_target:
+ raise ValueError(f'No main page target found for URL: {self.page.url}')
- await cdp_client.send.DOM.enable(session_id=session_id)
- await cdp_client.send.Accessibility.enable(session_id=session_id)
- await cdp_client.send.DOMSnapshot.enable(session_id=session_id)
- await cdp_client.send.Page.enable(session_id=session_id)
+ # Separate iframe targets for attachment
+ iframe_targets = [t for t in targets['targetInfos'] if t['type'] == 'iframe']
- return session_id
+ return CurrentPageTargets(
+ page_session=main_target,
+ iframe_sessions=iframe_targets,
+ )
+
+ async def _attach_target_activate_domains_get_session_id(self, target: TargetInfo) -> str:
+ """This function is cached, so go crazy"""
- raise ValueError(f'No session id found for page {self.page.url}')
+ cdp_client = await self._get_cdp_client()
+
+ target_id = str(target['targetId'])
+
+ if target_id in self.target_to_session_id_cache:
+ return self.target_to_session_id_cache[target_id]
+
+ session = await cdp_client.send.Target.attachToTarget(params={'targetId': target_id, 'flatten': True})
+ session_id = session['sessionId']
+
+ await cdp_client.send.Target.setAutoAttach(
+ params={
+ 'autoAttach': True,
+ 'waitForDebuggerOnStart': False,
+ 'flatten': True,
+ },
+ session_id=session_id,
+ )
+
+ await asyncio.gather(
+ cdp_client.send.DOM.enable(session_id=session_id),
+ cdp_client.send.Accessibility.enable(session_id=session_id),
+ cdp_client.send.DOMSnapshot.enable(session_id=session_id),
+ cdp_client.send.Page.enable(session_id=session_id),
+ )
+
+ self.target_to_session_id_cache[target_id] = session_id
+
+ return session_id
def _build_enhanced_ax_node(self, ax_node: AXNode) -> EnhancedAXNode:
properties: list[EnhancedAXProperty] | None = None
@@ -140,18 +169,15 @@ class DomService:
)
return enhanced_ax_node
- async def _get_viewport_size(self) -> tuple[float, float, float, float, float]:
+ async def _get_viewport_ratio(self, session_id: str) -> float:
"""Get viewport dimensions, device pixel ratio, and scroll position using CDP."""
try:
cdp_client = await self._get_cdp_client()
- session_id = await self._get_current_page_session_id()
# Get the layout metrics which includes the visual viewport
metrics = await cdp_client.send.Page.getLayoutMetrics(session_id=session_id)
visual_viewport = metrics.get('visualViewport', {})
- layout_viewport = metrics.get('layoutViewport', {})
- content_size = metrics.get('contentSize', {})
# IMPORTANT: Use CSS viewport instead of device pixel viewport
# This fixes the coordinate mismatch on high-DPI displays
@@ -160,22 +186,17 @@ class DomService:
# Use CSS pixels (what JavaScript sees) instead of device pixels
width = css_visual_viewport.get('clientWidth', css_layout_viewport.get('clientWidth', 1920.0))
- height = css_visual_viewport.get('clientHeight', css_layout_viewport.get('clientHeight', 1080.0))
# Calculate device pixel ratio
device_width = visual_viewport.get('clientWidth', width)
css_width = css_visual_viewport.get('clientWidth', width)
device_pixel_ratio = device_width / css_width if css_width > 0 else 1.0
- # Get current scroll position from the visual viewport
- scroll_x = css_visual_viewport.get('pageX', 0)
- scroll_y = css_visual_viewport.get('pageY', 0)
-
- return float(width), float(height), float(device_pixel_ratio), float(scroll_x), float(scroll_y)
+ return float(device_pixel_ratio)
except Exception as e:
print(f'⚠️ Viewport size detection failed: {e}')
# Fallback to default viewport size
- return 1920.0, 1080.0, 1.0, 0.0, 0.0
+ return 1.0
@classmethod
def is_element_visible_according_to_all_parents(
@@ -201,9 +222,6 @@ class DomService:
except (ValueError, TypeError):
pass
- if node.attributes.get('onclick', '') == "handleShadowIframeClick('S1')":
- pass
-
# Start with the element's local bounds (in its own frame's coordinate system)
current_bounds = node.snapshot_node.bounds
@@ -238,10 +256,10 @@ class DomService:
frame_bottom = frame.snapshot_node.scrollRects.y + frame.snapshot_node.clientRects.height
frame_intersects = (
- current_bounds.x > frame_left
- and current_bounds.x + current_bounds.width < frame_right
- and current_bounds.y > frame_top
- and current_bounds.y + current_bounds.height < frame_bottom
+ current_bounds.x < frame_right
+ and current_bounds.x + current_bounds.width > frame_left
+ and current_bounds.y < frame_bottom
+ and current_bounds.y + current_bounds.height > frame_top
)
if not frame_intersects:
@@ -250,9 +268,98 @@ class DomService:
# If we reach here, element is visible in main viewport and all containing iframes
return True
- async def _build_enhanced_dom_tree(
- self, dom_tree: GetDocumentReturns, ax_tree: GetFullAXTreeReturns, snapshot: CaptureSnapshotReturns
+ async def _get_ax_tree_for_all_frames(self, session_id: str) -> GetFullAXTreeReturns:
+ """Recursively collect all frames and merge their accessibility trees into a single array."""
+
+ cdp_client = await self._get_cdp_client()
+
+ frame_tree = await cdp_client.send.Page.getFrameTree(session_id=session_id)
+
+ def collect_all_frame_ids(frame_tree_node) -> list[str]:
+ """Recursively collect all frame IDs from the frame tree."""
+ frame_ids = [frame_tree_node['frame']['id']]
+
+ if 'childFrames' in frame_tree_node and frame_tree_node['childFrames']:
+ for child_frame in frame_tree_node['childFrames']:
+ frame_ids.extend(collect_all_frame_ids(child_frame))
+
+ return frame_ids
+
+ # Collect all frame IDs recursively
+ all_frame_ids = collect_all_frame_ids(frame_tree['frameTree'])
+
+ # Get accessibility tree for each frame
+ ax_tree_requests = []
+ for frame_id in all_frame_ids:
+ ax_tree_request = cdp_client.send.Accessibility.getFullAXTree(params={'frameId': frame_id}, session_id=session_id)
+ ax_tree_requests.append(ax_tree_request)
+
+ # Wait for all requests to complete
+ ax_trees = await asyncio.gather(*ax_tree_requests)
+
+ # Merge all AX nodes into a single array
+ merged_nodes: list[AXNode] = []
+ for ax_tree in ax_trees:
+ merged_nodes.extend(ax_tree['nodes'])
+
+ return {'nodes': merged_nodes}
+
+ async def _get_all_trees_for_session_id(self, session_id: str) -> TargetAllTrees:
+ if not self.browser.cdp_url:
+ raise ValueError('CDP URL is not set')
+
+ cdp_client = await self._get_cdp_client()
+
+ snapshot_request = cdp_client.send.DOMSnapshot.captureSnapshot(
+ params={
+ 'computedStyles': REQUIRED_COMPUTED_STYLES,
+ 'includePaintOrder': True,
+ 'includeDOMRects': True,
+ 'includeBlendedBackgroundColors': False,
+ 'includeTextColorOpacities': False,
+ },
+ session_id=session_id,
+ )
+
+ dom_tree_request = cdp_client.send.DOM.getDocument(params={'depth': -1, 'pierce': True}, session_id=session_id)
+
+ ax_tree_request = self._get_ax_tree_for_all_frames(session_id)
+
+ device_pixel_ratio_request = self._get_viewport_ratio(session_id)
+
+ start = time.time()
+ snapshot, dom_tree, ax_tree, device_pixel_ratio = await asyncio.gather(
+ snapshot_request, dom_tree_request, ax_tree_request, device_pixel_ratio_request
+ )
+ 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,
+ dom_tree=dom_tree,
+ ax_tree=ax_tree,
+ device_pixel_ratio=device_pixel_ratio,
+ cdp_timing=cdp_timing,
+ )
+
+ async def get_dom_tree(
+ self,
+ target: TargetInfo,
+ initial_html_frames: list[EnhancedDOMTreeNode] | None = None,
+ initial_total_frame_offset: DOMRect | None = None,
) -> EnhancedDOMTreeNode:
+ # 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)
+
+ dom_tree = trees.dom_tree
+ ax_tree = trees.ax_tree
+ snapshot = trees.snapshot
+ device_pixel_ratio = trees.device_pixel_ratio
+
ax_tree_lookup: dict[int, AXNode] = {
ax_node['backendDOMNodeId']: ax_node for ax_node in ax_tree['nodes'] if 'backendDOMNodeId' in ax_node
}
@@ -260,13 +367,10 @@ class DomService:
enhanced_dom_tree_node_lookup: dict[int, EnhancedDOMTreeNode] = {}
""" NodeId (NOT backend node id) -> enhanced dom tree node""" # way to get the parent/content node
- # Get viewport dimensions first for visibility calculation
- viewport_width, viewport_height, device_pixel_ratio, scroll_x, scroll_y = await self._get_viewport_size()
-
# Parse snapshot data with everything calculated upfront
snapshot_lookup = build_snapshot_lookup(snapshot, device_pixel_ratio)
- def _construct_enhanced_node(
+ async def _construct_enhanced_node(
node: Node, html_frames: list[EnhancedDOMTreeNode] | None, total_frame_offset: DOMRect | None
) -> EnhancedDOMTreeNode:
"""
@@ -370,7 +474,7 @@ class DomService:
total_frame_offset.y += snapshot_data.bounds.y
if 'contentDocument' in node and node['contentDocument']:
- dom_tree_node.content_document = _construct_enhanced_node(
+ dom_tree_node.content_document = await _construct_enhanced_node(
node['contentDocument'], updated_html_frames, total_frame_offset
)
dom_tree_node.content_document.parent_node = dom_tree_node
@@ -379,7 +483,7 @@ class DomService:
if 'shadowRoots' in node and node['shadowRoots']:
dom_tree_node.shadow_roots = []
for shadow_root in node['shadowRoots']:
- shadow_root_node = _construct_enhanced_node(shadow_root, updated_html_frames, total_frame_offset)
+ shadow_root_node = await _construct_enhanced_node(shadow_root, updated_html_frames, total_frame_offset)
# forcefully set the parent node to the shadow root node (helps traverse the tree)
shadow_root_node.parent_node = dom_tree_node
dom_tree_node.shadow_roots.append(shadow_root_node)
@@ -387,93 +491,41 @@ class DomService:
if 'children' in node and node['children']:
dom_tree_node.children_nodes = []
for child in node['children']:
- dom_tree_node.children_nodes.append(_construct_enhanced_node(child, updated_html_frames, total_frame_offset))
+ dom_tree_node.children_nodes.append(
+ await _construct_enhanced_node(child, updated_html_frames, total_frame_offset)
+ )
# Set visibility using the collected HTML frames
dom_tree_node.is_visible = self.is_element_visible_according_to_all_parents(dom_tree_node, updated_html_frames)
- return dom_tree_node
-
- enhanced_dom_tree_node = _construct_enhanced_node(dom_tree['root'], None, None)
-
- return enhanced_dom_tree_node
-
- async def _get_ax_tree_for_all_frames(self, cdp_client: CDPClient, session_id: str) -> GetFullAXTreeReturns:
- """Recursively collect all frames and merge their accessibility trees into a single array."""
- frame_tree = await cdp_client.send.Page.getFrameTree(session_id=session_id)
-
- def collect_all_frame_ids(frame_tree_node) -> list[str]:
- """Recursively collect all frame IDs from the frame tree."""
- frame_ids = [frame_tree_node['frame']['id']]
-
- if 'childFrames' in frame_tree_node and frame_tree_node['childFrames']:
- for child_frame in frame_tree_node['childFrames']:
- frame_ids.extend(collect_all_frame_ids(child_frame))
-
- return frame_ids
-
- # Collect all frame IDs recursively
- all_frame_ids = collect_all_frame_ids(frame_tree['frameTree'])
-
- # Get accessibility tree for each frame
- ax_tree_requests = []
- for frame_id in all_frame_ids:
- ax_tree_request = cdp_client.send.Accessibility.getFullAXTree(params={'frameId': frame_id}, session_id=session_id)
- ax_tree_requests.append(ax_tree_request)
-
- # Wait for all requests to complete
- ax_trees = await asyncio.gather(*ax_tree_requests)
-
- # Merge all AX nodes into a single array
- merged_nodes: list[AXNode] = []
- for ax_tree in ax_trees:
- merged_nodes.extend(ax_tree['nodes'])
-
- return {'nodes': merged_nodes}
-
- async def _get_all_trees(self) -> tuple[CaptureSnapshotReturns, GetDocumentReturns, GetFullAXTreeReturns, dict[str, float]]:
- if not self.browser.cdp_url:
- raise ValueError('CDP URL is not set')
-
- session_id = await self._get_current_page_session_id()
- cdp_client = await self._get_cdp_client()
-
- snapshot_request = cdp_client.send.DOMSnapshot.captureSnapshot(
- params={
- 'computedStyles': REQUIRED_COMPUTED_STYLES,
- 'includePaintOrder': True,
- 'includeDOMRects': True,
- 'includeBlendedBackgroundColors': False,
- 'includeTextColorOpacities': False,
- },
- session_id=session_id,
- )
-
- dom_tree_request = cdp_client.send.DOM.getDocument(params={'depth': -1, 'pierce': True}, session_id=session_id)
-
- ax_tree_request = self._get_ax_tree_for_all_frames(cdp_client, session_id)
-
- start = time.time()
- snapshot, dom_tree, ax_tree = await asyncio.gather(snapshot_request, dom_tree_request, ax_tree_request)
- end = time.time()
- cdp_timing = {'cdp_calls_total': end - start}
- print(f'Time taken to get dom tree: {end - start} seconds')
-
- return snapshot, dom_tree, ax_tree, cdp_timing
+ # handle cross origin iframe (just recursively call the main function with the proper target if it exists in iframes)
+ # only do this if the iframe is visible (otherwise it's not worth it)
+ if (
+ 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
+ )
+ # if target actually exists in one of the frames, just recursively build the dom tree for it
+ if iframe_document_target:
+ print(f'🔍 Getting content document for iframe {node.get("frameId", None)}')
+ content_document = await self.get_dom_tree(
+ iframe_document_target,
+ # 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,
+ initial_total_frame_offset=total_frame_offset,
+ )
- async def get_dom_tree(self) -> tuple[EnhancedDOMTreeNode, dict[str, float]]:
- snapshot, dom_tree, ax_tree, cdp_timing = await self._get_all_trees()
+ dom_tree_node.content_document = content_document
+ dom_tree_node.content_document.parent_node = dom_tree_node
- start = time.time()
- enhanced_dom_tree = await self._build_enhanced_dom_tree(dom_tree, ax_tree, snapshot)
- end = time.time()
+ return dom_tree_node
- build_tree_timing = {'build_enhanced_dom_tree': end - start}
- print(f'Time taken to build enhanced dom tree: {end - start} seconds')
+ enhanced_dom_tree_node = await _construct_enhanced_node(dom_tree['root'], initial_html_frames, initial_total_frame_offset)
- # Combine timing info
- all_timing = {**cdp_timing, **build_tree_timing}
- return enhanced_dom_tree, all_timing
+ return enhanced_dom_tree_node
async def get_serialized_dom_tree(
self, previous_cached_state: SerializedDOMState | None = None
@@ -482,7 +534,9 @@ class DomService:
TODO: this is a bit of a hack, we should probably have a better way to do this
"""
- enhanced_dom_tree, dom_timing = await self.get_dom_tree()
+
+ page_session_info = await self._get_targets_for_current_page()
+ enhanced_dom_tree = await self.get_dom_tree(page_session_info.page_session)
start = time.time()
serialized_dom_state, serializer_timing = DOMTreeSerializer(
@@ -494,5 +548,6 @@ class DomService:
print(f'Time taken to serialize dom tree: {end - start} seconds')
# Combine all timing info
- all_timing = {**dom_timing, **serializer_timing, **serialize_total_timing}
+ all_timing = {**serializer_timing, **serialize_total_timing}
+
return serialized_dom_state, all_timing
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 549fcc60c..54b96f021 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -3,8 +3,12 @@ from dataclasses import asdict, dataclass
from enum import Enum
from typing import Any
+from cdp_use.cdp.accessibility.commands import GetFullAXTreeReturns
from cdp_use.cdp.accessibility.types import AXPropertyName
+from cdp_use.cdp.dom.commands import GetDocumentReturns
from cdp_use.cdp.dom.types import ShadowRootType
+from cdp_use.cdp.domsnapshot.commands import CaptureSnapshotReturns
+from cdp_use.cdp.target.types import TargetInfo
from browser_use.dom.utils import cap_text_length
@@ -26,6 +30,24 @@ DEFAULT_INCLUDE_ATTRIBUTES = [
]
+@dataclass
+class CurrentPageTargets:
+ page_session: TargetInfo
+ iframe_sessions: list[TargetInfo]
+ """
+ Iframe sessions are ALL the iframes sessions of all the pages (not just the current page)
+ """
+
+
+@dataclass
+class TargetAllTrees:
+ snapshot: CaptureSnapshotReturns
+ dom_tree: GetDocumentReturns
+ ax_tree: GetFullAXTreeReturns
+ device_pixel_ratio: float
+ cdp_timing: dict[str, float]
+
+
@dataclass(slots=True)
class SimplifiedNode:
"""Simplified tree node for optimization."""