Skip to content

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

Improve Text Input Handling in Browser Context

XxAlonexX2965f12e4c61
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index 80cdbbb02..11693cfb3 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -910,6 +910,10 @@ class BrowserContext:
return None
async def _input_text_element_node(self, element_node: DOMElementNode, text: str):
+ """
+ Input text into an element with proper error handling and state management.
+ Handles different types of input fields and ensures proper element state before input.
+ """
try:
# Highlight before typing
if element_node.highlight_index is not None:
@@ -919,15 +923,42 @@ class BrowserContext:
element_handle = await self.get_locate_element(element_node)
if element_handle is None:
- raise Exception(f'Element: {repr(element_node)} not found')
+ raise BrowserError(f'Element: {repr(element_node)} not found')
+ # Ensure element is ready for input
+ await element_handle.wait_for_element_state('stable', timeout=2500)
await element_handle.scroll_into_view_if_needed(timeout=2500)
- await element_handle.fill('')
- await element_handle.type(text)
- await page.wait_for_load_state()
-
+
+ # Get element properties to determine input method
+ is_contenteditable = await element_handle.get_property('isContentEditable')
+ tag_name = await element_handle.get_property('tagName')
+ input_type = await element_handle.get_attribute('type')
+
+ # Different handling for contenteditable vs input fields
+ if await is_contenteditable.json_value():
+ await element_handle.evaluate('el => el.textContent = ""')
+ await element_handle.type(text, delay=50)
+ else:
+ try:
+ await element_handle.fill(text)
+ except Exception as fill_error:
+ logger.debug(f'Fill failed, trying type method. Error: {str(fill_error)}')
+ await element_handle.click()
+ await element_handle.press_sequentially(text, delay=50)
+
+ # Wait for input to be processed
+ await page.wait_for_load_state('networkidle', timeout=2500)
+
+ # Verify input was successful
+ if input_type != 'password': # Don't verify passwords for security
+ value = await element_handle.input_value()
+ if not value and text:
+ raise BrowserError('Input verification failed: text not present in element after input')
+
+ except BrowserError as e:
+ raise e
except Exception as e:
- raise Exception(f'Failed to input text into element: {repr(element_node)}. Error: {str(e)}')
+ raise BrowserError(f'Failed to input text into element: {repr(element_node)}. Error: {str(e)}')
async def _click_element_node(self, element_node: DOMElementNode) -> Optional[str]:
"""