Skip to content

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

auto-refresh state when desired element idx is not found

Nick Sweeting8daaaf665c95
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index bcd4669c2..508dbd3a2 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -1469,13 +1469,28 @@ class BrowserSession(BaseModel):
return await perform_click(lambda: element_handle.click(timeout=1500))
except URLNotAllowedError as e:
raise e
- except Exception:
- try:
- return await perform_click(lambda: page.evaluate('(el) => el.click()', element_handle))
- except URLNotAllowedError as e:
- raise e
- except Exception as e:
- raise Exception(f'Failed to click element: {type(e).__name__}: {e}')
+ except Exception as e:
+ # Check if it's a context error and provide more info
+ if 'Cannot find context with specified id' in str(e) or 'Protocol error' in str(e):
+ self.logger.warning(f'⚠️ Element context lost, attempting to re-locate element: {type(e).__name__}')
+ # Try to re-locate the element
+ element_handle = await self.get_locate_element(element_node)
+ if element_handle is None:
+ raise Exception(f'Element no longer exists in DOM after context loss: {repr(element_node)}')
+ # Try click again with fresh element
+ try:
+ return await perform_click(lambda: element_handle.click(timeout=1500))
+ except Exception:
+ # Fall back to JavaScript click
+ return await perform_click(lambda: page.evaluate('(el) => el.click()', element_handle))
+ else:
+ # Original fallback for other errors
+ try:
+ return await perform_click(lambda: page.evaluate('(el) => el.click()', element_handle))
+ except URLNotAllowedError as e:
+ raise e
+ except Exception as e:
+ raise Exception(f'Failed to click element: {type(e).__name__}: {e}')
except URLNotAllowedError as e:
raise e
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 2c5d53dc4..7af12fd85 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -128,8 +128,16 @@ class Controller(Generic[Context]):
async def click_element_by_index(params: ClickElementAction, browser_session: BrowserSession):
# Browser is now a BrowserSession itself
- if params.index not in await browser_session.get_selector_map():
- raise Exception(f'Element with index {params.index} does not exist - retry or use alternative actions')
+ # Check if element exists in current selector map
+ selector_map = await browser_session.get_selector_map()
+ if params.index not in selector_map:
+ # Force a state refresh in case the cache is stale
+ logger.info(f'Element with index {params.index} not found in selector map, refreshing state...')
+ await browser_session._update_state() # This will refresh the cached state
+ selector_map = await browser_session.get_selector_map()
+
+ if params.index not in selector_map:
+ raise Exception(f'Element with index {params.index} does not exist - retry or use alternative actions')
element_node = await browser_session.get_dom_element_by_index(params.index)
initial_pages = len(browser_session.tabs)
@@ -158,8 +166,15 @@ class Controller(Generic[Context]):
await browser_session.switch_to_tab(-1)
return ActionResult(extracted_content=msg, include_in_memory=True)
except Exception as e:
- logger.warning(f'Element not clickable with index {params.index} - most likely the page changed')
- return ActionResult(error=str(e))
+ error_msg = str(e)
+ if 'Execution context was destroyed' in error_msg or 'Cannot find context with specified id' in error_msg:
+ # Page navigated during click - refresh state and return it
+ logger.info('Page context changed during click, refreshing state...')
+ await browser_session._update_state()
+ return ActionResult(error='Page navigated during click. Refreshed state provided.', include_in_memory=True)
+ else:
+ logger.warning(f'Element not clickable with index {params.index} - most likely the page changed')
+ return ActionResult(error=error_msg)
@self.registry.action(
'Input text into a input interactive element',