Skip to content

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

added highllights natively

Gregor Žuničc3f0b8ddb11c
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 763413397..3f05c705a 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -17,6 +17,7 @@ from typing import Any, Self
from urllib.parse import urlparse
from browser_use.config import CONFIG
+from browser_use.dom.debug.highlights import inject_highlighting_script, remove_highlighting_script
from browser_use.dom.service import DomService
from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode, SerializedDOMState
from browser_use.observability import observe_debug
@@ -1963,20 +1964,26 @@ class BrowserSession(BaseModel):
page = await self.get_current_page()
await page.wait_for_selector(selector, state='visible', timeout=timeout)
+ @observe_debug(name='inject_highlights', ignore_output=True, ignore_input=True)
+ @require_initialization
+ @time_execution_async('--inject_highlights')
+ @retry(timeout=10, retries=0)
+ async def inject_highlights(self, dom_service: DomService, selector_map: DOMSelectorMap):
+ """Inject highlights into the page."""
+ await inject_highlighting_script(dom_service, selector_map)
+
@observe_debug(name='remove_highlights', ignore_output=True, ignore_input=True)
@require_initialization
@time_execution_async('--remove_highlights')
@retry(timeout=10, retries=0)
- async def remove_highlights(self):
+ async def remove_highlights(self, dom_service: DomService):
"""
DEPRECATED
Removes all highlight overlays and labels created by the highlightElement function.
Handles cases where the page might be closed or inaccessible.
-
- TODO: this function has been deprecated, we will create new debug method
"""
- return
+ await remove_highlighting_script(dom_service)
@require_initialization
async def get_dom_element_by_index(self, index: int) -> EnhancedDOMTreeNode | None:
@@ -2072,15 +2079,15 @@ class BrowserSession(BaseModel):
raise e
except Exception as e:
# Final fallback - try clicking by coordinates if available
- if element_node.snapshot_node and element_node.snapshot_node.clientRects:
+ if element_node.snapshot_node and element_node.snapshot_node.bounds:
try:
# TODO: instead of using the cached center, we should use the actual center of the element (easy, just get it by nodeBackendId)
self.logger.warning(
- f'⚠️ Element click failed, falling back to coordinate click at ({element_node.snapshot_node.clientRects.center.x}, {element_node.snapshot_node.clientRects.center.y})'
+ f'⚠️ Element click failed, falling back to coordinate click at ({element_node.snapshot_node.bounds.center.x}, {element_node.snapshot_node.bounds.center.y})'
)
await page.mouse.click(
- element_node.snapshot_node.clientRects.center.x,
- element_node.snapshot_node.clientRects.center.y,
+ element_node.snapshot_node.bounds.center.x,
+ element_node.snapshot_node.bounds.center.y,
)
try:
await page.wait_for_load_state()
@@ -2926,9 +2933,9 @@ class BrowserSession(BaseModel):
try:
self.logger.debug('🧹 Removing highlights...')
- await self.remove_highlights()
self.logger.debug('🌳 Starting DOM processing...')
async with DomService(self, page) as dom_service:
+ await self.remove_highlights(dom_service)
try:
dom_state = await asyncio.wait_for(
dom_service.get_serialized_dom_tree(
@@ -2938,6 +2945,9 @@ class BrowserSession(BaseModel):
),
timeout=45.0, # 45 second timeout for DOM processing - generous for complex pages
)
+
+ await self.inject_highlights(dom_service, dom_state.selector_map)
+
self.logger.debug('✅ DOM processing completed')
except TimeoutError:
self.logger.warning(f'DOM processing timed out after 45 seconds for {page.url}')
@@ -3025,6 +3035,8 @@ class BrowserSession(BaseModel):
if hasattr(self, 'browser_state_summary'):
return self.browser_state_summary
raise
+ finally:
+ await self.remove_highlights(dom_service)
# region - Browser Actions
@observe_debug(name='take_screenshot')
diff --git a/browser_use/dom/debug/highlights.py b/browser_use/dom/debug/highlights.py
index 4ba186dc6..e565a3a38 100644
--- a/browser_use/dom/debug/highlights.py
+++ b/browser_use/dom/debug/highlights.py
@@ -67,7 +67,7 @@ def convert_dom_selector_map_to_highlight_format(selector_map: DOMSelectorMap) -
bbox = None
if node.snapshot_node:
# Try bounds first, then clientRects
- rect = node.snapshot_node.bounds or node.snapshot_node.clientRects
+ rect = node.snapshot_node.bounds
if rect:
bbox = {'x': rect.x, 'y': rect.y, 'width': rect.width, 'height': rect.height}
@@ -98,27 +98,6 @@ def convert_dom_selector_map_to_highlight_format(selector_map: DOMSelectorMap) -
elements.append(element)
else:
- # Handle elements without valid bounding boxes (fallback for highlighting)
- # print(f'⚠️ Element {interactive_index} ({node.node_name}) has no valid bounding box, using fallback positioning')
- # element = {
- # 'x': 0,
- # 'y': 0,
- # 'width': 50,
- # 'height': 20,
- # 'interactive_index': interactive_index,
- # 'element_name': node.node_name,
- # 'is_clickable': node.snapshot_node.is_clickable if node.snapshot_node else True,
- # 'is_scrollable': getattr(node, 'is_scrollable', False),
- # 'attributes': node.attributes or {},
- # 'frame_id': getattr(node, 'frame_id', None),
- # 'node_id': node.node_id,
- # 'backend_node_id': node.backend_node_id,
- # 'xpath': node.xpath,
- # 'text_content': node.get_all_children_text()[:50]
- # if hasattr(node, 'get_all_children_text')
- # else node.node_value[:50],
- # }
-
# Skip elements without valid bounding boxes for now
# Could add fallback positioning here if needed
pass
@@ -187,13 +166,21 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen
container.id = 'browser-use-debug-highlights';
container.setAttribute('data-browser-use-highlight', 'container');
container.style.cssText = `
- position: absolute;
+ position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 999999;
+ overflow: hidden;
+ margin: 0;
+ padding: 0;
+ border: none;
+ outline: none;
+ box-shadow: none;
+ background: none;
+ font-family: inherit;
`;
// Helper function to create text nodes safely (CSP-friendly)
@@ -215,11 +202,16 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen
top: ${{element.y}}px;
width: ${{element.width}}px;
height: ${{element.height}}px;
- border: 2px solid #4a90e2;
+ outline: 2px solid #4a90e2;
+ outline-offset: -2px;
background-color: rgba(74, 144, 226, 0.1);
pointer-events: none;
- box-sizing: border-box;
+ box-sizing: content-box;
transition: all 0.2s ease;
+ margin: 0;
+ padding: 0;
+ border: none;
+ box-shadow: inset 0 0 0 2px #4a90e2;
`;
// Enhanced label with interactive index
@@ -237,6 +229,10 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen
white-space: nowrap;
z-index: 1000001;
box-shadow: 0 2px 4px rgba(0,0,0,0.3);
+ border: none;
+ outline: none;
+ margin: 0;
+ line-height: 1.2;
`);
// Enhanced tooltip with detailed reasoning (CSP-safe)
@@ -264,6 +260,7 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen
white-space: normal;
line-height: 1.4;
min-width: 200px;
+ margin: 0;
`;
// Build detailed tooltip content with reasoning (CSP-safe DOM creation)
@@ -276,20 +273,24 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen
// Determine confidence color and styling
let confidenceColor = '#4a90e2';
let confidenceIcon = '🔍';
- let borderColor = '#4a90e2';
+ let outlineColor = '#4a90e2';
+ let shadowColor = '#4a90e2';
if (confidence === 'HIGH') {{
confidenceColor = '#28a745';
confidenceIcon = '✅';
- borderColor = '#28a745';
+ outlineColor = '#28a745';
+ shadowColor = '#28a745';
}} else if (confidence === 'MEDIUM') {{
confidenceColor = '#ffc107';
confidenceIcon = '⚠️';
- borderColor = '#ffc107';
+ outlineColor = '#ffc107';
+ shadowColor = '#ffc107';
}} else {{
confidenceColor = '#fd7e14';
confidenceIcon = '❓';
- borderColor = '#fd7e14';
+ outlineColor = '#fd7e14';
+ shadowColor = '#fd7e14';
}}
// Create tooltip header
@@ -379,16 +380,17 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen
tooltip.appendChild(reasonsContainer);
tooltip.appendChild(boundsDiv);
- // Set highlight border color based on confidence
- highlight.style.borderColor = borderColor;
- label.style.backgroundColor = borderColor;
+ // Set highlight colors based on confidence
+ highlight.style.outline = `2px solid ${{outlineColor}}`;
+ highlight.style.boxShadow = `inset 0 0 0 2px ${{shadowColor}}`;
+ label.style.backgroundColor = outlineColor;
// Add hover effects
highlight.addEventListener('mouseenter', () => {{
- highlight.style.borderColor = '#ff6b6b';
+ highlight.style.outline = '3px solid #ff6b6b';
+ highlight.style.outlineOffset = '-3px';
highlight.style.backgroundColor = 'rgba(255, 107, 107, 0.2)';
- highlight.style.borderWidth = '3px';
- highlight.style.boxShadow = '0 0 10px rgba(255, 107, 107, 0.5)';
+ highlight.style.boxShadow = 'inset 0 0 0 3px #ff6b6b, 0 0 10px rgba(255, 107, 107, 0.5)';
tooltip.style.opacity = '1';
tooltip.style.visibility = 'visible';
label.style.backgroundColor = '#ff6b6b';
@@ -396,13 +398,13 @@ async def inject_highlighting_script(dom_service: DomService, interactive_elemen
}});
highlight.addEventListener('mouseleave', () => {{
- highlight.style.borderColor = borderColor;
+ highlight.style.outline = `2px solid ${{outlineColor}}`;
+ highlight.style.outlineOffset = '-2px';
highlight.style.backgroundColor = 'rgba(74, 144, 226, 0.1)';
- highlight.style.borderWidth = '2px';
- highlight.style.boxShadow = 'none';
+ highlight.style.boxShadow = `inset 0 0 0 2px ${{shadowColor}}`;
tooltip.style.opacity = '0';
tooltip.style.visibility = 'hidden';
- label.style.backgroundColor = borderColor;
+ label.style.backgroundColor = outlineColor;
label.style.transform = 'scale(1)';
}});
diff --git a/browser_use/dom/enhanced_snapshot.py b/browser_use/dom/enhanced_snapshot.py
index c3b9d7d48..232411c67 100644
--- a/browser_use/dom/enhanced_snapshot.py
+++ b/browser_use/dom/enhanced_snapshot.py
@@ -205,7 +205,7 @@ def build_snapshot_lookup(
cursor_style=cursor_style,
is_visible=is_visible,
bounds=bounding_box,
- clientRects=client_rects,
+ # clientRects=client_rects,
computed_styles=computed_styles if computed_styles else None,
paint_order=paint_order,
stacking_contexts=stacking_contexts,
diff --git a/browser_use/dom/playground/extraction.py b/browser_use/dom/playground/extraction.py
index 095d06323..5a6ddcb4c 100644
--- a/browser_use/dom/playground/extraction.py
+++ b/browser_use/dom/playground/extraction.py
@@ -65,9 +65,9 @@ async def test_focus_vs_all_elements():
async with DomService(browser_session, page) as dom_service:
await remove_highlighting_script(dom_service)
- all_elements_state = await dom_service.get_serialized_dom_tree()
+ # all_elements_state = await dom_service.get_serialized_dom_tree()
- await inject_highlighting_script(dom_service, all_elements_state.selector_map)
+ # await inject_highlighting_script(dom_service, all_elements_state.selector_map)
print(f'\n{"=" * 50}\nTesting {website}\n{"=" * 50}')
@@ -79,6 +79,9 @@ async def test_focus_vs_all_elements():
end_time = time.time()
print(f'get_state_summary took {end_time - start_time:.2f} seconds')
+ async with DomService(browser_session, page) as dom_service:
+ await inject_highlighting_script(dom_service, all_elements_state.dom_state.selector_map)
+
selector_map = all_elements_state.dom_state.selector_map
total_elements = len(selector_map.keys())
print(f'Total number of elements: {total_elements}')
diff --git a/browser_use/dom/serializer/serializer.py b/browser_use/dom/serializer/serializer.py
index 2354dccbc..82b3c7361 100644
--- a/browser_use/dom/serializer/serializer.py
+++ b/browser_use/dom/serializer/serializer.py
@@ -3,8 +3,6 @@
from dataclasses import dataclass, field
from enum import Enum
-from cdp_use.cdp.accessibility.types import AXPropertyName
-
from browser_use.dom.utils import cap_text_length
from browser_use.dom.views import DOMSelectorMap, EnhancedDOMTreeNode, NodeType, SerializedDOMState, SimplifiedNode
@@ -285,8 +283,8 @@ class ElementAnalysis:
score_boost = 0
if cls._is_ax_focusable(node):
- score_boost += 30
- evidence.append('Accessibility tree marked as focusable (+30)')
+ score_boost += 200 # ALWAYS detected - score guaranteed to exceed any threshold
+ evidence.append('ALWAYS DETECTED: Accessibility tree marked as focusable (+200)')
if node.ax_node and node.ax_node.role:
role = node.ax_node.role.lower()
@@ -312,7 +310,7 @@ class ElementAnalysis:
"""Check if element is focusable according to accessibility tree."""
if node.ax_node and node.ax_node.properties:
for prop in node.ax_node.properties:
- if prop.name == AXPropertyName.FOCUSABLE and prop.value:
+ if prop.name == 'focusable' and prop.value:
return True
return False
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index 5f679cb1c..332784514 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -5,9 +5,9 @@ from typing import TYPE_CHECKING
import httpx
from cdp_use import CDPClient
from cdp_use.cdp.accessibility.commands import GetFullAXTreeReturns
-from cdp_use.cdp.accessibility.types import AXNode, AXPropertyName
+from cdp_use.cdp.accessibility.types import AXNode
from cdp_use.cdp.dom.commands import GetDocumentReturns
-from cdp_use.cdp.dom.types import Node, ShadowRootType
+from cdp_use.cdp.dom.types import Node
from cdp_use.cdp.domsnapshot.commands import CaptureSnapshotReturns
from browser_use.dom.enhanced_snapshot import (
@@ -119,7 +119,6 @@ class DomService:
for property in ax_node['properties']:
try:
# test whether property name can go into the enum (sometimes Chrome returns some random properties)
- AXPropertyName(property['name'])
properties.append(
EnhancedAXProperty(
name=property['name'],
@@ -215,7 +214,7 @@ class DomService:
shadow_root_type = None
if 'shadowRootType' in node and node['shadowRootType']:
try:
- shadow_root_type = ShadowRootType(node['shadowRootType'])
+ shadow_root_type = node['shadowRootType']
except ValueError:
pass
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 43b46c758..463132352 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -112,7 +112,7 @@ class EnhancedSnapshotNode:
Typical use: Quick hit-test that doesn’t care about scroll position.
"""
- clientRects: DOMRect | None
+ # clientRects: DOMRect | None
"""
Viewport coordinates (origin = top-left of the visible scrollport).
Equivalent JS API: element.getClientRects() / getBoundingClientRect().
@@ -255,7 +255,7 @@ class EnhancedDOMTreeNode:
'is_scrollable': self.is_scrollable,
'frame_id': self.frame_id,
'content_document': self.content_document.__json__() if self.content_document else None,
- 'shadow_root_type': self.shadow_root_type.value if self.shadow_root_type else None,
+ 'shadow_root_type': self.shadow_root_type,
'ax_node': asdict(self.ax_node) if self.ax_node else None,
'snapshot_node': asdict(self.snapshot_node) if self.snapshot_node else None,
# these two in the end, so it's easier to read json
diff --git a/pyproject.toml b/pyproject.toml
index 1bf8d8d57..5a233d392 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.1",
+ "cdp-use>=1.3.2",
]
# google-api-core: only used for Google LLM APIs
# pyperclip: only used for examples that use copy/paste