Skip to content

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

feat: Add ARIA menu support to dropdown functions

claude[bot]a72da4150944
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 489a130ee..e7044cc54 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -811,10 +811,10 @@ Explain the content of the page and that the requested information is not availa
)
@self.registry.action(
- description='Get all options from a native dropdown',
+ description='Get all options from a native dropdown or ARIA menu',
)
async def get_dropdown_options(index: int, browser_session: BrowserSession) -> ActionResult:
- """Get all options from a native dropdown"""
+ """Get all options from a native dropdown or ARIA menu"""
page = await browser_session.get_current_page()
selector_map = await browser_session.get_selector_map()
dom_element = selector_map[index]
@@ -826,30 +826,65 @@ Explain the content of the page and that the requested information is not availa
for frame in page.frames:
try:
+ # First check if it's a native select element
options = await frame.evaluate(
"""
(xpath) => {
- const select = document.evaluate(xpath, document, null,
+ const element = document.evaluate(xpath, document, null,
XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
- if (!select) return null;
-
- return {
- options: Array.from(select.options).map(opt => ({
- text: opt.text, //do not trim, because we are doing exact match in select_dropdown_option
- value: opt.value,
- index: opt.index
- })),
- id: select.id,
- name: select.name
- };
+ if (!element) return null;
+
+ // Check if it's a native select element
+ if (element.tagName.toLowerCase() === 'select') {
+ return {
+ type: 'select',
+ options: Array.from(element.options).map(opt => ({
+ text: opt.text, //do not trim, because we are doing exact match in select_dropdown_option
+ value: opt.value,
+ index: opt.index
+ })),
+ id: element.id,
+ name: element.name
+ };
+ }
+
+ // Check if it's an ARIA menu
+ if (element.getAttribute('role') === 'menu' ||
+ element.getAttribute('role') === 'listbox' ||
+ element.getAttribute('role') === 'combobox') {
+ // Find all menu items
+ const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');
+ const options = [];
+
+ menuItems.forEach((item, idx) => {
+ // Get the text content of the menu item
+ const text = item.textContent.trim();
+ if (text) {
+ options.push({
+ text: text,
+ value: text, // For ARIA menus, use text as value
+ index: idx
+ });
+ }
+ });
+
+ return {
+ type: 'aria',
+ options: options,
+ id: element.id || '',
+ name: element.getAttribute('aria-label') || ''
+ };
+ }
+
+ return null;
}
""",
dom_element.xpath,
)
if options:
- logger.debug(f'Found dropdown in frame {frame_index}')
- logger.debug(f'Dropdown ID: {options["id"]}, Name: {options["name"]}')
+ logger.debug(f'Found {options["type"]} dropdown in frame {frame_index}')
+ logger.debug(f'Element ID: {options["id"]}, Name: {options["name"]}')
formatted_options = []
for opt in options['options']:
@@ -888,24 +923,18 @@ Explain the content of the page and that the requested information is not availa
return ActionResult(extracted_content=msg, include_in_memory=True)
@self.registry.action(
- description='Select dropdown option for interactive element index by the text of the option you want to select',
+ description='Select dropdown option or ARIA menu item for interactive element index by the text of the option you want to select',
)
async def select_dropdown_option(
index: int,
text: str,
browser_session: BrowserSession,
) -> ActionResult:
- """Select dropdown option by the text of the option you want to select"""
+ """Select dropdown option or ARIA menu item by the text of the option you want to select"""
page = await browser_session.get_current_page()
selector_map = await browser_session.get_selector_map()
dom_element = selector_map[index]
- # Validate that we're working with a select element
- if dom_element.tag_name != 'select':
- logger.error(f'Element is not a select! Tag: {dom_element.tag_name}, Attributes: {dom_element.attributes}')
- msg = f'Cannot select option: Element with index {index} is a {dom_element.tag_name}, not a select'
- return ActionResult(extracted_content=msg, include_in_memory=True, long_term_memory=msg)
-
logger.debug(f"Attempting to select '{text}' using xpath: {dom_element.xpath}")
logger.debug(f'Element attributes: {dom_element.attributes}')
logger.debug(f'Element tag: {dom_element.tag_name}')
@@ -918,27 +947,48 @@ Explain the content of the page and that the requested information is not availa
try:
logger.debug(f'Trying frame {frame_index} URL: {frame.url}')
- # First verify we can find the dropdown in this frame
- find_dropdown_js = """
+ # First check what type of element we're dealing with
+ element_info_js = """
(xpath) => {
try {
- const select = document.evaluate(xpath, document, null,
+ const element = document.evaluate(xpath, document, null,
XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
- if (!select) return null;
- if (select.tagName.toLowerCase() !== 'select') {
+ if (!element) return null;
+
+ const tagName = element.tagName.toLowerCase();
+ const role = element.getAttribute('role');
+
+ // Check if it's a native select
+ if (tagName === 'select') {
return {
- error: `Found element but it's a ${select.tagName}, not a SELECT`,
- found: false
+ type: 'select',
+ found: true,
+ id: element.id,
+ name: element.name,
+ tagName: element.tagName,
+ optionCount: element.options.length,
+ currentValue: element.value,
+ availableOptions: Array.from(element.options).map(o => o.text.trim())
};
}
+
+ // Check if it's an ARIA menu or similar
+ if (role === 'menu' || role === 'listbox' || role === 'combobox') {
+ const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');
+ return {
+ type: 'aria',
+ found: true,
+ id: element.id || '',
+ role: role,
+ tagName: element.tagName,
+ itemCount: menuItems.length,
+ availableOptions: Array.from(menuItems).map(item => item.textContent.trim())
+ };
+ }
+
return {
- id: select.id,
- name: select.name,
- found: true,
- tagName: select.tagName,
- optionCount: select.options.length,
- currentValue: select.value,
- availableOptions: Array.from(select.options).map(o => o.text.trim())
+ error: `Element is neither a select nor an ARIA menu (tag: ${tagName}, role: ${role})`,
+ found: false
};
} catch (e) {
return {error: e.toString(), found: false};
@@ -946,28 +996,90 @@ Explain the content of the page and that the requested information is not availa
}
"""
- dropdown_info = await frame.evaluate(find_dropdown_js, dom_element.xpath)
-
- if dropdown_info:
- if not dropdown_info.get('found'):
- logger.error(f'Frame {frame_index} error: {dropdown_info.get("error")}')
- continue
-
- logger.debug(f'Found dropdown in frame {frame_index}: {dropdown_info}')
-
- # "label" because we are selecting by text
- # nth(0) to disable error thrown by strict mode
- # timeout=1000 because we are already waiting for all network events, therefore ideally we don't need to wait a lot here (default 30s)
- selected_option_values = (
- await frame.locator('//' + dom_element.xpath).nth(0).select_option(label=text, timeout=1000)
- )
-
- msg = f'selected option {text} with value {selected_option_values}'
- logger.info(msg + f' in frame {frame_index}')
-
- return ActionResult(
- extracted_content=msg, include_in_memory=True, long_term_memory=f"Selected option '{text}'"
- )
+ element_info = await frame.evaluate(element_info_js, dom_element.xpath)
+
+ if element_info and element_info.get('found'):
+ logger.debug(f'Found {element_info.get("type")} element in frame {frame_index}: {element_info}')
+
+ if element_info.get('type') == 'select':
+ # Handle native select element
+ # "label" because we are selecting by text
+ # nth(0) to disable error thrown by strict mode
+ # timeout=1000 because we are already waiting for all network events
+ selected_option_values = (
+ await frame.locator('//' + dom_element.xpath).nth(0).select_option(label=text, timeout=1000)
+ )
+
+ msg = f'selected option {text} with value {selected_option_values}'
+ logger.info(msg + f' in frame {frame_index}')
+
+ return ActionResult(
+ extracted_content=msg, include_in_memory=True, long_term_memory=f"Selected option '{text}'"
+ )
+
+ elif element_info.get('type') == 'aria':
+ # Handle ARIA menu
+ click_aria_item_js = """
+ (params) => {
+ const { xpath, targetText } = params;
+ try {
+ const element = document.evaluate(xpath, document, null,
+ XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
+ if (!element) return {success: false, error: 'Element not found'};
+
+ // Find all menu items
+ const menuItems = element.querySelectorAll('[role="menuitem"], [role="option"]');
+
+ for (const item of menuItems) {
+ const itemText = item.textContent.trim();
+ if (itemText === targetText) {
+ // Simulate click on the menu item
+ item.click();
+
+ // Also try dispatching a click event in case the click handler needs it
+ const clickEvent = new MouseEvent('click', {
+ view: window,
+ bubbles: true,
+ cancelable: true
+ });
+ item.dispatchEvent(clickEvent);
+
+ return {
+ success: true,
+ message: `Clicked menu item: ${targetText}`
+ };
+ }
+ }
+
+ return {
+ success: false,
+ error: `Menu item with text '${targetText}' not found`
+ };
+ } catch (e) {
+ return {success: false, error: e.toString()};
+ }
+ }
+ """
+
+ result = await frame.evaluate(
+ click_aria_item_js, {'xpath': dom_element.xpath, 'targetText': text}
+ )
+
+ if result.get('success'):
+ msg = result.get('message', f'Selected ARIA menu item: {text}')
+ logger.info(msg + f' in frame {frame_index}')
+ return ActionResult(
+ extracted_content=msg,
+ include_in_memory=True,
+ long_term_memory=f"Selected menu item '{text}'",
+ )
+ else:
+ logger.error(f'Failed to select ARIA menu item: {result.get("error")}')
+ continue
+
+ elif element_info:
+ logger.error(f'Frame {frame_index} error: {element_info.get("error")}')
+ continue
except Exception as frame_e:
logger.error(f'Frame {frame_index} attempt failed: {str(frame_e)}')
diff --git a/tests/ci/test_aria_menu_dropdown.py b/tests/ci/test_aria_menu_dropdown.py
new file mode 100644
index 000000000..dc069e4ee
--- /dev/null
+++ b/tests/ci/test_aria_menu_dropdown.py
@@ -0,0 +1,320 @@
+import pytest
+from pytest_httpserver import HTTPServer
+
+from browser_use.agent.views import ActionModel, ActionResult
+from browser_use.browser import BrowserSession
+from browser_use.browser.profile import BrowserProfile
+from browser_use.controller.service import Controller
+from browser_use.controller.views import GoToUrlAction
+
+
[email protected](scope='session')
+def http_server():
+ """Create and provide a test HTTP server that serves static content."""
+ server = HTTPServer()
+ server.start()
+
+ # Add route for ARIA menu test page
+ server.expect_request('/aria-menu').respond_with_data(
+ """
+ <!DOCTYPE html>
+ <html>
+ <head>
+ <title>ARIA Menu Test</title>
+ <style>
+ .menu {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+ border: 1px solid #ccc;
+ background: white;
+ width: 200px;
+ }
+ .menu-item {
+ padding: 10px 20px;
+ border-bottom: 1px solid #eee;
+ }
+ .menu-item:hover {
+ background: #f0f0f0;
+ }
+ .menu-item-anchor {
+ text-decoration: none;
+ color: #333;
+ display: block;
+ }
+ #result {
+ margin-top: 20px;
+ padding: 10px;
+ border: 1px solid #ddd;
+ min-height: 20px;
+ }
+ </style>
+ </head>
+ <body>
+ <h1>ARIA Menu Test</h1>
+ <p>This menu uses ARIA roles instead of native select elements</p>
+
+ <!-- Exactly like the HTML provided in the issue -->
+ <ul class="menu menu-format-standard menu-regular" role="menu" id="pyNavigation1752753375773" style="display: block;">
+ <li class="menu-item menu-item-enabled" role="presentation">
+ <a href="#" onclick="pd(event);" class="menu-item-anchor" tabindex="0" role="menuitem">
+ <span class="menu-item-title-wrap"><span class="menu-item-title">Filter</span></span>
+ </a>
+ </li>
+ <li class="menu-item menu-item-enabled" role="presentation" id="menu-item-$PpyNavigation1752753375773$ppyElements$l2">
+ <a href="#" onclick="pd(event);" class="menu-item-anchor menu-item-expand" tabindex="0" role="menuitem" aria-haspopup="true">
+ <span class="menu-item-title-wrap"><span class="menu-item-title">Sort</span></span>
+ </a>
+ <div class="menu-panel-wrapper">
+ <ul class="menu menu-format-standard menu-regular" role="menu" id="$PpyNavigation1752753375773$ppyElements$l2">
+ <li class="menu-item menu-item-enabled" role="presentation">
+ <a href="#" onclick="pd(event);" class="menu-item-anchor" tabindex="0" role="menuitem">
+ <span class="menu-item-title-wrap"><span class="menu-item-title">Lowest to highest</span></span>
+ </a>
+ </li>
+ <li class="menu-item menu-item-enabled" role="presentation">
+ <a href="#" onclick="pd(event);" class="menu-item-anchor" tabindex="0" role="menuitem">
+ <span class="menu-item-title-wrap"><span class="menu-item-title">Highest to lowest</span></span>
+ </a>
+ </li>
+ </ul>
+ </div>
+ </li>
+ <li class="menu-item menu-item-enabled" role="presentation">
+ <a href="#" onclick="pd(event);" class="menu-item-anchor" tabindex="0" role="menuitem">
+ <span class="menu-item-title-wrap"><span class="menu-item-title">Appearance</span></span>
+ </a>
+ </li>
+ <li class="menu-item menu-item-enabled" role="presentation">
+ <a href="#" onclick="pd(event);" class="menu-item-anchor" tabindex="0" role="menuitem">
+ <span class="menu-item-title-wrap"><span class="menu-item-title">Summarize</span></span>
+ </a>
+ </li>
+ <li class="menu-item menu-item-enabled" role="presentation">
+ <a href="#" onclick="pd(event);" class="menu-item-anchor" tabindex="0" role="menuitem">
+ <span class="menu-item-title-wrap"><span class="menu-item-title">Delete</span></span>
+ </a>
+ </li>
+ </ul>
+
+ <div id="result">Click an option to see the result</div>
+
+ <script>
+ // Mock the pd function that prevents default
+ function pd(event) {
+ event.preventDefault();
+ const text = event.target.closest('[role="menuitem"]').textContent.trim();
+ document.getElementById('result').textContent = 'Clicked: ' + text;
+ }
+ </script>
+ </body>
+ </html>
+ """,
+ content_type='text/html',
+ )
+
+ yield server
+ server.stop()
+
+
[email protected](scope='session')
+def base_url(http_server):
+ """Return the base URL for the test HTTP server."""
+ return f'http://{http_server.host}:{http_server.port}'
+
+
[email protected](scope='module')
+async def browser_session():
+ """Create and provide a Browser instance with security disabled."""
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
+ headless=True,
+ user_data_dir=None,
+ keep_alive=True,
+ )
+ )
+ await browser_session.start()
+ yield browser_session
+ await browser_session.kill()
+
+
[email protected](scope='function')
+def controller():
+ """Create and provide a Controller instance."""
+ return Controller()
+
+
+class TestARIAMenuDropdown:
+ """Test ARIA menu support for get_dropdown_options and select_dropdown_option."""
+
+ async def test_get_dropdown_options_with_aria_menu(self, controller, browser_session: BrowserSession, base_url):
+ """Test that get_dropdown_options can retrieve options from ARIA menus."""
+ # Navigate to the ARIA menu test page
+ goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/aria-menu', new_tab=False)}
+
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: GoToUrlAction | None = None
+
+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+
+ # Wait for the page to load
+ page = await browser_session.get_current_page()
+ await page.wait_for_load_state()
+
+ # Initialize the DOM state to populate the selector map
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=True)
+
+ # Get the selector map
+ selector_map = await browser_session.get_selector_map()
+
+ # Find the ARIA menu element in the selector map
+ menu_index = None
+ for idx, element in selector_map.items():
+ # Look for the UL with role="menu"
+ if element.tag_name.lower() == 'ul' and 'menu' in str(element.attributes.get('role', '')):
+ menu_index = idx
+ break
+
+ assert menu_index is not None, (
+ f'Could not find ARIA menu element in selector map. Available elements: {[f"{idx}: {element.tag_name}" for idx, element in selector_map.items()]}'
+ )
+
+ # Create a model for the get_dropdown_options action
+ class GetDropdownOptionsModel(ActionModel):
+ get_dropdown_options: dict[str, int]
+
+ # Execute the action with the menu index
+ result = await controller.act(
+ action=GetDropdownOptionsModel(get_dropdown_options={'index': menu_index}),
+ browser_session=browser_session,
+ )
+
+ # Verify the result structure
+ assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
+
+ # Expected ARIA menu options
+ expected_options = ['Filter', 'Sort', 'Appearance', 'Summarize', 'Delete']
+
+ # Verify all options are returned
+ for option in expected_options:
+ assert option in result.extracted_content, f"Option '{option}' not found in result content"
+
+ # Verify the instruction for using the text in select_dropdown_option is included
+ assert 'Use the exact text string in select_dropdown_option' in result.extracted_content
+
+ async def test_select_dropdown_option_with_aria_menu(self, controller, browser_session: BrowserSession, base_url):
+ """Test that select_dropdown_option can select an option from ARIA menus."""
+ # Navigate to the ARIA menu test page
+ goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/aria-menu', new_tab=False)}
+
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: GoToUrlAction | None = None
+
+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+
+ # Wait for the page to load
+ page = await browser_session.get_current_page()
+ await page.wait_for_load_state()
+
+ # Initialize the DOM state to populate the selector map
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=True)
+
+ # Get the selector map
+ selector_map = await browser_session.get_selector_map()
+
+ # Find the ARIA menu element in the selector map
+ menu_index = None
+ for idx, element in selector_map.items():
+ # Look for the UL with role="menu"
+ if element.tag_name.lower() == 'ul' and 'menu' in str(element.attributes.get('role', '')):
+ menu_index = idx
+ break
+
+ assert menu_index is not None, (
+ f'Could not find ARIA menu element in selector map. Available elements: {[f"{idx}: {element.tag_name}" for idx, element in selector_map.items()]}'
+ )
+
+ # Create a model for the select_dropdown_option action
+ class SelectDropdownOptionModel(ActionModel):
+ select_dropdown_option: dict
+
+ # Execute the action with the menu index to select "Filter"
+ result = await controller.act(
+ SelectDropdownOptionModel(select_dropdown_option={'index': menu_index, 'text': 'Filter'}),
+ browser_session,
+ )
+
+ # Verify the result structure
+ assert isinstance(result, ActionResult)
+
+ # Core logic validation: Verify selection was successful
+ assert result.extracted_content is not None
+ assert 'selected option' in result.extracted_content.lower() or 'clicked' in result.extracted_content.lower()
+ assert 'Filter' in result.extracted_content
+
+ # Verify the click actually had an effect on the page
+ result_text = await page.evaluate("document.getElementById('result').textContent")
+ assert 'Filter' in result_text, f"Expected 'Filter' in result text, got '{result_text}'"
+
+ async def test_get_dropdown_options_with_nested_aria_menu(self, controller, browser_session: BrowserSession, base_url):
+ """Test that get_dropdown_options can handle nested ARIA menus (like Sort submenu)."""
+ # Navigate to the ARIA menu test page
+ goto_action = {'go_to_url': GoToUrlAction(url=f'{base_url}/aria-menu', new_tab=False)}
+
+ class GoToUrlActionModel(ActionModel):
+ go_to_url: GoToUrlAction | None = None
+
+ await controller.act(GoToUrlActionModel(**goto_action), browser_session)
+
+ # Wait for the page to load
+ page = await browser_session.get_current_page()
+ await page.wait_for_load_state()
+
+ # Initialize the DOM state to populate the selector map
+ await browser_session.get_state_summary(cache_clickable_elements_hashes=True)
+
+ # Get the selector map
+ selector_map = await browser_session.get_selector_map()
+
+ # Find the nested ARIA menu element in the selector map
+ nested_menu_index = None
+ for idx, element in selector_map.items():
+ # Look for the nested UL with id containing "$PpyNavigation"
+ if (
+ element.tag_name.lower() == 'ul'
+ and '$PpyNavigation' in str(element.attributes.get('id', ''))
+ and element.attributes.get('role') == 'menu'
+ ):
+ nested_menu_index = idx
+ break
+
+ # The nested menu might not be in the selector map initially if it's hidden
+ # In that case, we should test the main menu
+ if nested_menu_index is None:
+ # Find the main menu instead
+ for idx, element in selector_map.items():
+ if element.tag_name.lower() == 'ul' and element.attributes.get('id') == 'pyNavigation1752753375773':
+ nested_menu_index = idx
+ break
+
+ assert nested_menu_index is not None, (
+ f'Could not find any ARIA menu element in selector map. Available elements: {[f"{idx}: {element.tag_name}" for idx, element in selector_map.items()]}'
+ )
+
+ # Create a model for the get_dropdown_options action
+ class GetDropdownOptionsModel(ActionModel):
+ get_dropdown_options: dict[str, int]
+
+ # Execute the action with the menu index
+ result = await controller.act(
+ action=GetDropdownOptionsModel(get_dropdown_options={'index': nested_menu_index}),
+ browser_session=browser_session,
+ )
+
+ # Verify the result structure
+ assert isinstance(result, ActionResult)
+ assert result.extracted_content is not None
+
+ # The action should return some menu options
+ assert 'Use the exact text string in select_dropdown_option' in result.extracted_content