Skip to content

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

fix iframe scroll detection and viewport element inclusion tests after scroll

Nick Sweetingb3546b0cf564
diff --git a/browser_use/browser/default_action_watchdog.py b/browser_use/browser/default_action_watchdog.py
index da925c132..5ee463821 100644
--- a/browser_use/browser/default_action_watchdog.py
+++ b/browser_use/browser/default_action_watchdog.py
@@ -159,12 +159,29 @@ class DefaultActionWatchdog(BaseWatchdog):
element_node = event.node
index_for_logging = element_node.backend_node_id or 'unknown'
+ # Check if the element is an iframe
+ is_iframe = element_node.tag_name and element_node.tag_name.upper() == 'IFRAME'
+
# Try to scroll the element's container
success = await self._scroll_element_container(element_node, pixels)
if success:
self.logger.info(
f'πŸ“œ Scrolled element {index_for_logging} container {event.direction} by {event.amount} pixels'
)
+
+ # CRITICAL: For iframe scrolling, we need to force a full DOM refresh
+ # because the iframe's content has changed position
+ if is_iframe:
+ self.logger.debug('πŸ”„ Forcing DOM refresh after iframe scroll')
+ # Clear all caches to force complete DOM rebuild
+ self.browser_session._cached_browser_state_summary = None
+ self.browser_session._cached_selector_map.clear()
+ if self.browser_session._dom_watchdog:
+ self.browser_session._dom_watchdog.clear_cache()
+
+ # Wait a bit for the scroll to settle and DOM to update
+ await asyncio.sleep(0.5)
+
return None
# Perform target-level scroll
@@ -211,10 +228,9 @@ class DefaultActionWatchdog(BaseWatchdog):
raise Exception('Cannot click on file input elements. File uploads must be handled programmatically.')
# Get CDP client
- cdp_session = await self.browser_session.get_or_create_cdp_session()
+ cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=element_node.target_id, focus=False)
# Get the correct session ID for the element's frame
- # session_id = await self._get_session_id_for_element(element_node)
session_id = cdp_session.session_id
# Get element bounds
@@ -463,7 +479,7 @@ class DefaultActionWatchdog(BaseWatchdog):
timeout=1.0, # 1 second timeout for mouseReleased
)
except TimeoutError:
- self.logger.debug('⏱️ Mouse up timed out (likely due to dialog), continuing...')
+ self.logger.debug('⏱️ Mouse up timed out (possibly due to lag or dialog popup), continuing...')
self.logger.debug('πŸ–±οΈ Clicked successfully using x,y coordinates')
@@ -842,6 +858,63 @@ class DefaultActionWatchdog(BaseWatchdog):
try:
cdp_session = await self.browser_session.cdp_client_for_node(element_node)
+ # Check if this is an iframe - if so, scroll its content directly
+ if element_node.tag_name and element_node.tag_name.upper() == 'IFRAME':
+ # For iframes, we need to scroll the content document, not the iframe element itself
+ # Use JavaScript to directly scroll the iframe's content
+ backend_node_id = element_node.backend_node_id
+
+ # Resolve the node to get an object ID
+ result = await cdp_session.cdp_client.send.DOM.resolveNode(
+ params={'backendNodeId': backend_node_id},
+ session_id=cdp_session.session_id,
+ )
+
+ if 'object' in result and 'objectId' in result['object']:
+ object_id = result['object']['objectId']
+
+ # Scroll the iframe's content directly
+ scroll_result = await cdp_session.cdp_client.send.Runtime.callFunctionOn(
+ params={
+ 'functionDeclaration': f"""
+ function() {{
+ try {{
+ const doc = this.contentDocument || this.contentWindow.document;
+ if (doc) {{
+ const scrollElement = doc.documentElement || doc.body;
+ if (scrollElement) {{
+ const oldScrollTop = scrollElement.scrollTop;
+ scrollElement.scrollTop += {pixels};
+ const newScrollTop = scrollElement.scrollTop;
+ return {{
+ success: true,
+ oldScrollTop: oldScrollTop,
+ newScrollTop: newScrollTop,
+ scrolled: newScrollTop - oldScrollTop
+ }};
+ }}
+ }}
+ return {{success: false, error: 'Could not access iframe content'}};
+ }} catch (e) {{
+ return {{success: false, error: e.toString()}};
+ }}
+ }}
+ """,
+ 'objectId': object_id,
+ 'returnByValue': True,
+ },
+ session_id=cdp_session.session_id,
+ )
+
+ if scroll_result and 'result' in scroll_result and 'value' in scroll_result['result']:
+ result_value = scroll_result['result']['value']
+ if result_value.get('success'):
+ self.logger.debug(f'Successfully scrolled iframe content by {result_value.get("scrolled", 0)}px')
+ return True
+ else:
+ self.logger.debug(f'Failed to scroll iframe: {result_value.get("error", "Unknown error")}')
+
+ # For non-iframe elements, use the standard mouse wheel approach
# Get element bounds to know where to scroll
backend_node_id = element_node.backend_node_id
box_model = await cdp_session.cdp_client.send.DOM.getBoxModel(
diff --git a/browser_use/browser/downloads_watchdog.py b/browser_use/browser/downloads_watchdog.py
index 3dcad1ef6..b88ef485c 100644
--- a/browser_use/browser/downloads_watchdog.py
+++ b/browser_use/browser/downloads_watchdog.py
@@ -182,8 +182,8 @@ class DownloadsWatchdog(BaseWatchdog):
self._track_download(file_path)
# Register the handlers with CDP
- cdp_client.register.Browser.downloadWillBegin(download_will_begin_handler)
- cdp_client.register.Browser.downloadProgress(download_progress_handler)
+ cdp_client.register.Browser.downloadWillBegin(download_will_begin_handler) # type: ignore[arg-type]
+ cdp_client.register.Browser.downloadProgress(download_progress_handler) # type: ignore[arg-type]
self._download_cdp_session_setup = True
self.logger.debug('[DownloadsWatchdog] Set up CDP download listeners')
diff --git a/browser_use/browser/popups_watchdog.py b/browser_use/browser/popups_watchdog.py
index 93d1aae2a..9411526bf 100644
--- a/browser_use/browser/popups_watchdog.py
+++ b/browser_use/browser/popups_watchdog.py
@@ -75,7 +75,7 @@ class PopupsWatchdog(BaseWatchdog):
except Exception as e:
self.logger.error(f'Failed to accept dialog: {e}')
- cdp_session.cdp_client.register.Page.javascriptDialogOpening(handle_dialog)
+ cdp_session.cdp_client.register.Page.javascriptDialogOpening(handle_dialog) # type: ignore[arg-type]
self.logger.info(
f'βœ… Successfully registered Page.javascriptDialogOpening handler for session {cdp_session.session_id}'
)
diff --git a/browser_use/dom/serializer/clickable_elements.py b/browser_use/dom/serializer/clickable_elements.py
index c40a6b005..068bbdf50 100644
--- a/browser_use/dom/serializer/clickable_elements.py
+++ b/browser_use/dom/serializer/clickable_elements.py
@@ -17,6 +17,16 @@ class ClickableElementDetector:
# remove html and body nodes
if node.tag_name in {'html', 'body'}:
return False
+
+ # IFRAME elements should be interactive if they're large enough to potentially need scrolling
+ # Small iframes (< 100px width or height) are unlikely to have scrollable content
+ if node.tag_name and node.tag_name.upper() == 'IFRAME':
+ if node.snapshot_node and node.snapshot_node.bounds:
+ width = node.snapshot_node.bounds.width
+ height = node.snapshot_node.bounds.height
+ # Only include iframes larger than 100x100px
+ if width > 100 and height > 100:
+ return True
# RELAXED SIZE CHECK: Allow all elements including size 0 (they might be interactive overlays, etc.)
# Note: Size 0 elements can still be interactive (e.g., invisible clickable overlays)
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index aae4639e5..c31bccc8e 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -204,22 +204,44 @@ class DomService:
and frame.snapshot_node.scrollRects
and frame.snapshot_node.clientRects
):
- frame_left = frame.snapshot_node.scrollRects.x
- frame_top = frame.snapshot_node.scrollRects.y
- frame_right = frame.snapshot_node.scrollRects.x + frame.snapshot_node.clientRects.width
- frame_bottom = frame.snapshot_node.scrollRects.y + frame.snapshot_node.clientRects.height
-
+ # For iframe content, we need to check visibility within the iframe's viewport
+ # The scrollRects represent the current scroll position
+ # The clientRects represent the viewport size
+ # Elements are visible if they fall within the viewport after accounting for scroll
+
+ # The viewport of the frame (what's actually visible)
+ viewport_left = 0 # Viewport always starts at 0 in frame coordinates
+ viewport_top = 0
+ viewport_right = frame.snapshot_node.clientRects.width
+ viewport_bottom = frame.snapshot_node.clientRects.height
+
+ # Adjust element bounds by the scroll offset to get position relative to viewport
+ # When scrolled down, scrollRects.y is positive, so we subtract it from element's y
+ adjusted_x = current_bounds.x - frame.snapshot_node.scrollRects.x
+ adjusted_y = current_bounds.y - frame.snapshot_node.scrollRects.y
+
frame_intersects = (
- 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
+ adjusted_x < viewport_right
+ and adjusted_x + current_bounds.width > viewport_left
+ and adjusted_y < viewport_bottom
+ and adjusted_y + current_bounds.height > viewport_top
)
if not frame_intersects:
+ # DEBUG: Log why element is not visible
+ if node and node.attributes:
+ attrs = node.attributes
+ elem_id = attrs.get('id', '')
+ elem_name = attrs.get('name', '')
+ if 'city' in elem_id.lower() or 'city' in elem_name.lower() or \
+ 'state' in elem_id.lower() or 'state' in elem_name.lower() or \
+ 'zip' in elem_id.lower() or 'zip' in elem_name.lower():
+ import logging
+ logging.info(f"πŸ” DEBUG: Element id='{elem_id}' name='{elem_name}' not visible - adjusted bounds: x={adjusted_x}, y={adjusted_y}, w={current_bounds.width}, h={current_bounds.height}, viewport: {viewport_right}x{viewport_bottom}, scroll: x={frame.snapshot_node.scrollRects.x}, y={frame.snapshot_node.scrollRects.y}")
return False
- # negate the values added in `_construct_enhanced_node`
+ # Keep the original coordinate adjustment to maintain consistency
+ # This adjustment is needed for proper coordinate transformation
current_bounds.x -= frame.snapshot_node.scrollRects.x
current_bounds.y -= frame.snapshot_node.scrollRects.y
@@ -273,6 +295,45 @@ class DomService:
)
except Exception as e:
pass # Page might not be ready yet
+ # DEBUG: Log before capturing snapshot
+ self.logger.info(f"πŸ” DEBUG: Capturing DOM snapshot for target {target_id}")
+
+ # Get actual scroll positions for all iframes before capturing snapshot
+ iframe_scroll_positions = {}
+ try:
+ scroll_result = await cdp_session.cdp_client.send.Runtime.evaluate(
+ params={
+ 'expression': """
+ (() => {
+ const scrollData = {};
+ const iframes = document.querySelectorAll('iframe');
+ iframes.forEach((iframe, index) => {
+ try {
+ const doc = iframe.contentDocument || iframe.contentWindow.document;
+ if (doc) {
+ scrollData[index] = {
+ scrollTop: doc.documentElement.scrollTop || doc.body.scrollTop || 0,
+ scrollLeft: doc.documentElement.scrollLeft || doc.body.scrollLeft || 0
+ };
+ }
+ } catch (e) {
+ // Cross-origin iframe, can't access
+ }
+ });
+ return scrollData;
+ })()
+ """,
+ 'returnByValue': True
+ },
+ session_id=cdp_session.session_id
+ )
+ if scroll_result and 'result' in scroll_result and 'value' in scroll_result['result']:
+ iframe_scroll_positions = scroll_result['result']['value']
+ for idx, scroll_data in iframe_scroll_positions.items():
+ self.logger.info(f"πŸ” DEBUG: Iframe {idx} actual scroll position - scrollTop={scroll_data.get('scrollTop', 0)}, scrollLeft={scroll_data.get('scrollLeft', 0)}")
+ except Exception as e:
+ self.logger.debug(f"Failed to get iframe scroll positions: {e}")
+
snapshot_request = cdp_session.cdp_client.send.DOMSnapshot.captureSnapshot(
params={
'computedStyles': REQUIRED_COMPUTED_STYLES,
@@ -306,6 +367,15 @@ class DomService:
device_pixel_ratio = await asyncio.wait_for(device_pixel_ratio_request, timeout=2.0)
end = time.time()
cdp_timing = {'cdp_calls_total': end - start}
+
+ # DEBUG: Log snapshot info
+ if snapshot and 'documents' in snapshot:
+ total_nodes = sum(len(doc.get('nodes', [])) for doc in snapshot['documents'])
+ self.logger.info(f"πŸ” DEBUG: Snapshot contains {len(snapshot['documents'])} documents with {total_nodes} total nodes")
+ # Log iframe-specific info
+ for doc_idx, doc in enumerate(snapshot['documents']):
+ if doc_idx > 0: # Not the main document
+ self.logger.info(f"πŸ” DEBUG: Document {doc_idx} has {len(doc.get('nodes', []))} nodes")
return TargetAllTrees(
snapshot=snapshot,
@@ -444,6 +514,8 @@ class DomService:
if snapshot_data and snapshot_data.scrollRects:
total_frame_offset.x -= snapshot_data.scrollRects.x
total_frame_offset.y -= snapshot_data.scrollRects.y
+ # DEBUG: Log iframe scroll information
+ self.logger.info(f"πŸ” DEBUG: HTML frame scroll - scrollY={snapshot_data.scrollRects.y}, scrollX={snapshot_data.scrollRects.x}, frameId={node.get('frameId')}, nodeId={node['nodeId']}")
# Calculate new iframe offset for content documents, accounting for iframe scroll
if node['nodeName'].upper() == 'IFRAME' and snapshot_data and snapshot_data.bounds:
@@ -477,6 +549,16 @@ class DomService:
# 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)
+
+ # DEBUG: Log visibility info for form elements in iframes
+ if dom_tree_node.tag_name and dom_tree_node.tag_name.upper() in ['INPUT', 'SELECT', 'TEXTAREA', 'LABEL']:
+ attrs = dom_tree_node.attributes or {}
+ elem_id = attrs.get('id', '')
+ elem_name = attrs.get('name', '')
+ if 'city' in elem_id.lower() or 'city' in elem_name.lower() or \
+ 'state' in elem_id.lower() or 'state' in elem_name.lower() or \
+ 'zip' in elem_id.lower() or 'zip' in elem_name.lower():
+ self.logger.info(f"πŸ” DEBUG: Form element {dom_tree_node.tag_name} id='{elem_id}' name='{elem_name}' - visible={dom_tree_node.is_visible}, bounds={dom_tree_node.snapshot_node.bounds if dom_tree_node.snapshot_node else 'NO_SNAPSHOT'}")
# 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)
diff --git a/browser_use/logging_config.py b/browser_use/logging_config.py
index 2587a0dd2..ced8f5485 100644
--- a/browser_use/logging_config.py
+++ b/browser_use/logging_config.py
@@ -106,7 +106,7 @@ def setup_logging(stream=None, log_level=None, force_setup=False):
# Determine the log level to use
if log_type == 'result':
- log_level = 'RESULT' # string usage to avoid syntax error
+ log_level = 35 # RESULT level value
elif log_type == 'debug':
log_level = logging.DEBUG
else:
diff --git a/tests/scripts/debug_iframe_scrolling.py b/tests/scripts/debug_iframe_scrolling.py
new file mode 100644
index 000000000..99063c3d9
--- /dev/null
+++ b/tests/scripts/debug_iframe_scrolling.py
@@ -0,0 +1,305 @@
+"""
+Debug test for iframe scrolling issue where DOM tree only shows top elements after scrolling.
+
+This test verifies that after scrolling inside an iframe, the selector_map correctly
+contains lower input elements like City, State, Zip Code, etc.
+"""
+
+import asyncio
+import sys
+from pathlib import Path
+
+# Add parent directory to path to import browser_use modules
+sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+from browser_use.agent.service import Agent
+from browser_use.agent.views import ActionModel, AgentOutput
+from browser_use.browser import BrowserProfile, BrowserSession
+from browser_use.browser.events import BrowserStateRequestEvent
+from browser_use.controller.service import Controller
+from browser_use.controller.views import GoToUrlAction, ScrollAction
+
+# Import the mock LLM helper from conftest
+from tests.ci.conftest import create_mock_llm
+
+
+async def debug_iframe_scrolling():
+ """Debug iframe scrolling and DOM visibility issue."""
+
+ print("Starting iframe scrolling debug test...")
+
+ # Create the sequence of actions for the mock LLM
+ # We need to format these as the LLM would return them
+ actions = [
+ # First action: Navigate to the test URL
+ """
+ {
+ "thinking": "Navigating to the iframe test page",
+ "evaluation_previous_goal": null,
+ "memory": "Starting test",
+ "next_goal": "Navigate to the iframe test page",
+ "action": [
+ {
+ "go_to_url": {
+ "url": "https://browser-use.github.io/stress-tests/challenges/iframe-inception-level1.html",
+ "new_tab": false
+ }
+ }
+ ]
+ }
+ """,
+ # Second action: Input text in the first name field (to verify we can interact)
+ """
+ {
+ "thinking": "Inputting text in the first name field to test interaction",
+ "evaluation_previous_goal": "Successfully navigated to the page",
+ "memory": "Page loaded with nested iframes",
+ "next_goal": "Type text in the first name field",
+ "action": [
+ {
+ "input_text": {
+ "index": 1,
+ "text": "TestName"
+ }
+ }
+ ]
+ }
+ """,
+ # Third action: Scroll the iframe (element_index=2 should be the iframe)
+ """
+ {
+ "thinking": "Scrolling inside the iframe to reveal lower form elements",
+ "evaluation_previous_goal": "Successfully typed in first name field",
+ "memory": "Typed TestName in first field",
+ "next_goal": "Scroll inside the innermost iframe to see more form fields",
+ "action": [
+ {
+ "scroll": {
+ "down": true,
+ "num_pages": 1.0,
+ "index": 2
+ }
+ }
+ ]
+ }
+ """,
+ # Fourth action: Done
+ """
+ {
+ "thinking": "Completed scrolling, ready to inspect DOM",
+ "evaluation_previous_goal": "Successfully scrolled inside iframe",
+ "memory": "Scrolled to reveal lower form fields",
+ "next_goal": "Task completed",
+ "action": [
+ {
+ "done": {
+ "text": "Scrolling completed",
+ "success": true
+ }
+ }
+ ]
+ }
+ """
+ ]
+
+ # Create mock LLM with our action sequence
+ mock_llm = create_mock_llm(actions=actions)
+
+ # Create browser session with headless=False so we can see what's happening
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ headless=False, # Set to False to see the browser
+ user_data_dir=None, # Use temporary directory
+ keep_alive=True,
+ enable_default_extensions=True,
+ cross_origin_iframes=True, # Enable cross-origin iframe support
+ )
+ )
+
+ try:
+ # Start the browser session
+ await browser_session.start()
+ print("Browser session started")
+
+ # Create an agent with the mock LLM
+ agent = Agent(
+ task="Navigate to the iframe test page and scroll inside the iframe",
+ llm=mock_llm,
+ browser_session=browser_session,
+ )
+
+ # Helper function to capture and analyze DOM state
+ async def capture_dom_state(label: str) -> dict:
+ """Capture DOM state and return analysis"""
+ print(f"\nπŸ“Έ Capturing DOM state: {label}")
+ state_event = browser_session.event_bus.dispatch(
+ BrowserStateRequestEvent(
+ include_dom=True,
+ include_screenshot=False,
+ cache_clickable_elements_hashes=True,
+ include_recent_events=False
+ )
+ )
+ browser_state = await state_event.event_result()
+
+ if browser_state and browser_state.dom_state and browser_state.dom_state.selector_map:
+ selector_map = browser_state.dom_state.selector_map
+ element_count = len(selector_map)
+
+ # Check for specific elements
+ found_elements = {}
+ expected_checks = [
+ ("First Name", ["firstName", "first name"]),
+ ("Last Name", ["lastName", "last name"]),
+ ("Email", ["email"]),
+ ("City", ["city"]),
+ ("State", ["state"]),
+ ("Zip", ["zip", "zipCode"]),
+ ]
+
+ for name, keywords in expected_checks:
+ for index, element in selector_map.items():
+ element_str = str(element).lower()
+ if any(kw.lower() in element_str for kw in keywords):
+ found_elements[name] = True
+ break
+
+ return {
+ "label": label,
+ "total_elements": element_count,
+ "found_elements": found_elements,
+ "selector_map": selector_map
+ }
+ return {"label": label, "error": "No DOM state available"}
+
+ # Capture initial state before any actions
+ print("\n" + "="*80)
+ print("PHASE 1: INITIAL PAGE LOAD")
+ print("="*80)
+
+ # Navigate to the page first
+ from browser_use.controller.views import GoToUrlAction
+ from browser_use.controller.service import Controller
+ controller = Controller()
+
+ # Create the action model for navigation
+ goto_action = ActionModel.model_validate_json(actions[0])
+ await controller.act(goto_action, browser_session)
+ await asyncio.sleep(2) # Wait for page to fully load
+
+ initial_state = await capture_dom_state("INITIAL (after page load)")
+
+ # Now run the rest of the actions via the agent
+ print("\n" + "="*80)
+ print("PHASE 2: EXECUTING ACTIONS")
+ print("="*80)
+
+ # Create new agent with remaining actions
+ remaining_actions = actions[1:] # Skip the navigation we already did
+ mock_llm_remaining = create_mock_llm(actions=remaining_actions)
+ agent = Agent(
+ task="Input text and scroll inside the iframe",
+ llm=mock_llm_remaining,
+ browser_session=browser_session,
+ )
+
+ # Hook into agent actions to capture state after each one
+ states = []
+ original_act = controller.act
+ async def wrapped_act(action, session):
+ result = await original_act(action, session)
+ # Capture state after each action
+ action_type = "unknown"
+ if hasattr(action, 'input_text') and action.input_text:
+ action_type = "input_text"
+ await asyncio.sleep(1) # Give time for DOM to update
+ state = await capture_dom_state("AFTER INPUT_TEXT")
+ states.append(state)
+ elif hasattr(action, 'scroll') and action.scroll:
+ action_type = "scroll"
+ await asyncio.sleep(2) # Give more time after scroll
+ state = await capture_dom_state("AFTER SCROLL")
+ states.append(state)
+ return result
+
+ controller.act = wrapped_act
+
+ # Run the agent with remaining actions
+ result = await agent.run()
+ print(f"\nAgent completed with result: {result}")
+
+ # Analyze all captured states
+ print("\n" + "="*80)
+ print("PHASE 3: ANALYSIS OF DOM STATES")
+ print("="*80)
+
+ all_states = [initial_state] + states
+
+ for state in all_states:
+ if "error" in state:
+ print(f"\n❌ {state['label']}: {state['error']}")
+ else:
+ print(f"\nπŸ“Š {state['label']}:")
+ print(f" Total elements: {state['total_elements']}")
+ print(f" Found elements:")
+ for elem_name, found in state['found_elements'].items():
+ status = "βœ“" if found else "βœ—"
+ print(f" {status} {elem_name}")
+
+ # Compare states
+ print("\n" + "="*80)
+ print("COMPARISON SUMMARY")
+ print("="*80)
+
+ if len(all_states) >= 3:
+ initial = all_states[0]
+ after_input = all_states[1] if len(all_states) > 1 else None
+ after_scroll = all_states[2] if len(all_states) > 2 else None
+
+ print(f"\nElement count changes:")
+ print(f" Initial: {initial.get('total_elements', 0)} elements")
+ if after_input:
+ print(f" After input_text: {after_input.get('total_elements', 0)} elements")
+ if after_scroll:
+ print(f" After scroll: {after_scroll.get('total_elements', 0)} elements")
+
+ # Check if lower form fields appear after scroll
+ if after_scroll and "found_elements" in after_scroll:
+ lower_fields = ["City", "State", "Zip"]
+ missing_fields = [f for f in lower_fields if not after_scroll["found_elements"].get(f, False)]
+
+ if missing_fields:
+ print(f"\n⚠️ BUG CONFIRMED: Lower form fields missing after scroll:")
+ for field in missing_fields:
+ print(f" βœ— {field}")
+ print("\nThis confirms that scrolling inside iframes does not update the DOM tree properly.")
+ else:
+ print("\nβœ… SUCCESS: All lower form fields are visible after scrolling!")
+
+ # Show first few elements from final state for debugging
+ if states and "selector_map" in states[-1]:
+ print("\n" + "="*80)
+ print("DEBUG: First 5 elements in final selector_map")
+ print("="*80)
+ final_map = states[-1]["selector_map"]
+ for i, (index, element) in enumerate(list(final_map.items())[:5]):
+ elem_preview = str(element)[:150]
+ print(f"\n [{index}]: {elem_preview}...")
+
+ # Keep browser open for manual inspection if needed
+ print("\n" + "="*80)
+ print("Test complete. Browser will remain open for 10 seconds for inspection...")
+ print("="*80)
+ await asyncio.sleep(10)
+
+ finally:
+ # Clean up
+ print("\nCleaning up...")
+ await browser_session.kill()
+ await browser_session.event_bus.stop(clear=True, timeout=5)
+ print("Browser session closed")
+
+
+if __name__ == "__main__":
+ # Run the debug test
+ asyncio.run(debug_iframe_scrolling())
\ No newline at end of file