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
fixed out of viewport elements
Gregor Žuničbb253bf4f3ac
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.pyindex 267d04d31..763413397 100644--- a/browser_use/browser/session.py+++ b/browser_use/browser/session.py@@ -226,7 +226,7 @@ class BrowserSession(BaseModel):)_cached_browser_state_summary: BrowserStateSummary | None = PrivateAttr(default=None)- # _cached_clickable_element_hashes: CachedClickableElementHashes | None = PrivateAttr(default=None)+ _cached_clickable_element_hashes: CachedClickableElementHashes | None = PrivateAttr(default=None)_tab_visibility_callback: Any = PrivateAttr(default=None)_logger: logging.Logger | None = PrivateAttr(default=None)_downloaded_files: list[str] = PrivateAttr(default_factory=list)diff --git a/browser_use/dom/debug/highlights.py b/browser_use/dom/debug/highlights.pyindex ed37fdafa..027751236 100644--- a/browser_use/dom/debug/highlights.py+++ b/browser_use/dom/debug/highlights.py@@ -69,7 +69,7 @@ def convert_dom_selector_map_to_highlight_format(selector_map: DOMSelectorMap) -# Try bounds first, then clientRectsrect = node.snapshot_node.bounds or node.snapshot_node.clientRectsif rect:- bbox = {'x': rect.x / 2, 'y': rect.y / 2, 'width': rect.width / 2, 'height': rect.height / 2}+ bbox = {'x': rect.x, 'y': rect.y, 'width': rect.width, 'height': rect.height}# Only include elements with valid bounding boxes (following working implementation)if bbox and bbox.get('width', 0) > 0 and bbox.get('height', 0) > 0:diff --git a/browser_use/dom/enhanced_snapshot.py b/browser_use/dom/enhanced_snapshot.pyindex 60ad508ef..c3b9d7d48 100644--- a/browser_use/dom/enhanced_snapshot.py+++ b/browser_use/dom/enhanced_snapshot.py@@ -15,8 +15,9 @@ from cdp_use.cdp.domsnapshot.types import (from browser_use.dom.views import DOMRect, EnhancedSnapshotNode-# Only the essential computed styles we actually need+# Only the ESSENTIAL computed styles for interactivity and visibility detectionREQUIRED_COMPUTED_STYLES = [+ # Essential for visibility'display','visibility','opacity',@@ -60,9 +61,14 @@ def _parse_computed_styles(strings: list[str], style_indices: list[int]) -> dictdef _is_element_visible(- bounding_box: DOMRect, computed_styles: dict[str, str], viewport_width: float, viewport_height: float+ bounding_box: DOMRect,+ computed_styles: dict[str, str],+ viewport_width: float,+ viewport_height: float,+ scroll_x: float = 0.0,+ scroll_y: float = 0.0,) -> bool:- """Determine if an element is visible. More permissive - considers elements visible if they start anywhere on the page."""+ """Determine if an element is visible in the current scrolled viewport."""# Check if element has zero dimensionsif bounding_box.width <= 0 or bounding_box.height <= 0:return False@@ -81,18 +87,34 @@ def _is_element_visible(except (ValueError, TypeError):pass- # More permissive visibility - element is visible if it has any presence on the page- # and intersects with the viewport area (including elements that start at the beginning)+ # SCROLL-AWARE VISIBILITY: Check if element intersects with current scrolled viewport+ # Current viewport rectangle in document coordinates+ viewport_left = scroll_x+ viewport_top = scroll_y+ viewport_right = scroll_x + viewport_width+ viewport_bottom = scroll_y + viewport_height++ # Element rectangle in document coordinates+ elem_left = bounding_box.x+ elem_top = bounding_box.yelem_right = bounding_box.x + bounding_box.widthelem_bottom = bounding_box.y + bounding_box.height- # Element is visible if it has any intersection with the page area- # This includes elements that start at x=0, y=0 (beginning of page)- return elem_right > 0 and elem_bottom > 0 and bounding_box.x < viewport_width and bounding_box.y < viewport_height+ # Check if rectangles intersect (element is visible in current viewport)+ intersects = (+ elem_right > viewport_left and elem_left < viewport_right and elem_bottom > viewport_top and elem_top < viewport_bottom+ )++ return intersectsdef build_snapshot_lookup(- snapshot: CaptureSnapshotReturns, viewport_width: float, viewport_height: float+ snapshot: CaptureSnapshotReturns,+ viewport_width: float,+ viewport_height: float,+ device_pixel_ratio: float = 1.0,+ scroll_x: float = 0.0,+ scroll_y: float = 0.0,) -> dict[int, EnhancedSnapshotNode]:"""Build a lookup table of backend node ID to enhanced snapshot data with everything calculated upfront."""snapshot_lookup: dict[int, EnhancedSnapshotNode] = {}@@ -132,7 +154,17 @@ def build_snapshot_lookup(# Parse bounding boxbounds = layout['bounds'][layout_idx]if len(bounds) >= 4:- bounding_box = DOMRect(x=bounds[0], y=bounds[1], width=bounds[2], height=bounds[3])+ # IMPORTANT: CDP coordinates are in device pixels, convert to CSS pixels+ # by dividing by the device pixel ratio+ raw_x, raw_y, raw_width, raw_height = bounds[0], bounds[1], bounds[2], bounds[3]++ # Apply device pixel ratio scaling to convert device pixels to CSS pixels+ bounding_box = DOMRect(+ x=raw_x / device_pixel_ratio,+ y=raw_y / device_pixel_ratio,+ width=raw_width / device_pixel_ratio,+ height=raw_height / device_pixel_ratio,+ )# Parse computed styles for this layout nodeif layout_idx < len(layout.get('styles', [])):@@ -160,9 +192,11 @@ def build_snapshot_lookup(if layout_idx < len(layout.get('stackingContexts', [])):stacking_contexts = layout.get('stackingContexts', {}).get('index', [])[layout_idx]- # Calculate visibility immediately if we have bounding box+ # Calculate scroll-aware visibility if we have bounding boxif bounding_box and computed_styles:- is_visible = _is_element_visible(bounding_box, computed_styles, viewport_width, viewport_height)+ is_visible = _is_element_visible(+ bounding_box, computed_styles, viewport_width, viewport_height, scroll_x, scroll_y+ )breakdiff --git a/browser_use/dom/service.py b/browser_use/dom/service.pyindex 92c04b0f7..ccab4b9da 100644--- a/browser_use/dom/service.py+++ b/browser_use/dom/service.py@@ -140,23 +140,42 @@ class DomService:)return enhanced_ax_node- async def _get_viewport_size(self) -> tuple[float, float]:- """Get viewport dimensions using CDP."""+ async def _get_viewport_size(self) -> tuple[float, float, float, float, 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 viewportmetrics = await cdp_client.send.Page.getLayoutMetrics(session_id=session_id)- visual_viewport = metrics.get('visualViewport', {})-- width = visual_viewport.get('clientWidth', 1920.0)- height = visual_viewport.get('clientHeight', 1080.0)- return float(width), float(height)- except Exception:+ 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+ css_visual_viewport = metrics.get('cssVisualViewport', {})+ css_layout_viewport = metrics.get('cssLayoutViewport', {})++ # 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)+ except Exception as e:+ print(f'⚠️ Viewport size detection failed: {e}')# Fallback to default viewport size- return 1920.0, 1080.0+ return 1920.0, 1080.0, 1.0, 0.0, 0.0async def _build_enhanced_dom_tree(self, dom_tree: GetDocumentReturns, ax_tree: GetFullAXTreeReturns, snapshot: CaptureSnapshotReturns@@ -169,10 +188,11 @@ class DomService:""" 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 = await self._get_viewport_size()+ 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, viewport_width, viewport_height)+ # Parse snapshot data with everything calculated upfront+ snapshot_lookup = build_snapshot_lookup(snapshot, viewport_width, viewport_height, device_pixel_ratio, scroll_x, scroll_y)def _construct_enhanced_node(node: Node) -> EnhancedDOMTreeNode:# memoize the mf (I don't know if some nodes are duplicated)diff --git a/tests/ci/test_action_parameter_injection.py b/tests/ci/test_action_parameter_injection.pyindex 204edc452..b230d72bb 100644--- a/tests/ci/test_action_parameter_injection.py+++ b/tests/ci/test_action_parameter_injection.py@@ -293,46 +293,47 @@ class TestBrowserContext:tabs_info = await browser_session.get_tabs_info()assert len(tabs_info) == 1, 'Should have one tab open after closing the second'- @pytest.mark.asyncio- async def test_remove_highlights(self, browser_session, base_url):- """Test that remove_highlights successfully removes highlight elements."""- # Navigate to a test page- await browser_session.navigate(f'{base_url}/')-- # Add a highlight via JavaScript- await browser_session.execute_javascript("""- const container = document.createElement('div');- container.id = 'playwright-highlight-container';- document.body.appendChild(container);-- const highlight = document.createElement('div');- highlight.id = 'playwright-highlight-1';- container.appendChild(highlight);-- const element = document.querySelector('h1');- element.setAttribute('browser-user-highlight-id', 'playwright-highlight-1');- """)-- # Verify the highlight container exists- container_exists = await browser_session.execute_javascript(- "document.getElementById('playwright-highlight-container') !== null"- )- assert container_exists, 'Highlight container should exist before removal'-- # Call remove_highlights- await browser_session.remove_highlights()-- # Verify the highlight container was removed- container_exists_after = await browser_session.execute_javascript(- "document.getElementById('playwright-highlight-container') !== null"- )- assert not container_exists_after, 'Highlight container should be removed'-- # Verify the highlight attribute was removed from the element- attribute_exists = await browser_session.execute_javascript(- "document.querySelector('h1').hasAttribute('browser-user-highlight-id')"- )- assert not attribute_exists, 'browser-user-highlight-id attribute should be removed'+ # TODO: highlighting doesn't exist anymore+ # @pytest.mark.asyncio+ # async def test_remove_highlights(self, browser_session, base_url):+ # """Test that remove_highlights successfully removes highlight elements."""+ # # Navigate to a test page+ # await browser_session.navigate(f'{base_url}/')++ # # Add a highlight via JavaScript+ # await browser_session.execute_javascript("""+ # const container = document.createElement('div');+ # container.id = 'playwright-highlight-container';+ # document.body.appendChild(container);++ # const highlight = document.createElement('div');+ # highlight.id = 'playwright-highlight-1';+ # container.appendChild(highlight);++ # const element = document.querySelector('h1');+ # element.setAttribute('browser-user-highlight-id', 'playwright-highlight-1');+ # """)++ # # Verify the highlight container exists+ # container_exists = await browser_session.execute_javascript(+ # "document.getElementById('playwright-highlight-container') !== null"+ # )+ # assert container_exists, 'Highlight container should exist before removal'++ # # Call remove_highlights+ # await browser_session.remove_highlights()++ # # Verify the highlight container was removed+ # container_exists_after = await browser_session.execute_javascript(+ # "document.getElementById('playwright-highlight-container') !== null"+ # )+ # assert not container_exists_after, 'Highlight container should be removed'++ # # Verify the highlight attribute was removed from the element+ # attribute_exists = await browser_session.execute_javascript(+ # "document.querySelector('h1').hasAttribute('browser-user-highlight-id')"+ # )+ # assert not attribute_exists, 'browser-user-highlight-id attribute should be removed'@pytest.mark.asyncioasync def test_custom_action_with_no_arguments(self, browser_session, base_url):