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
fix: auto-switch to new tabs after click and add checkbox toggle fallback
Saurav Pandae7a05cbe86d7
diff --git a/browser_use/browser/watchdogs/default_action_watchdog.py b/browser_use/browser/watchdogs/default_action_watchdog.pyindex f9c17147d..85acfab45 100644--- a/browser_use/browser/watchdogs/default_action_watchdog.py+++ b/browser_use/browser/watchdogs/default_action_watchdog.py@@ -724,6 +724,32 @@ class DefaultActionWatchdog(BaseWatchdog):# Get element boundsbackend_node_id = element_node.backend_node_id+ # For checkbox/radio: capture pre-click state to verify toggle worked+ is_toggle_element = tag_name == 'input' and element_type in ('checkbox', 'radio')+ pre_click_checked: bool | None = None+ checkbox_object_id: str | None = None+ if is_toggle_element and backend_node_id:+ try:+ resolve_res = await cdp_session.cdp_client.send.DOM.resolveNode(+ params={'backendNodeId': backend_node_id}, session_id=session_id+ )+ obj_info = resolve_res.get('object', {})+ checkbox_object_id = obj_info.get('objectId') if obj_info else None+ if not checkbox_object_id:+ raise Exception('Failed to resolve checkbox element objectId')+ state_res = await cdp_session.cdp_client.send.Runtime.callFunctionOn(+ params={+ 'functionDeclaration': 'function() { return this.checked; }',+ 'objectId': checkbox_object_id,+ 'returnByValue': True,+ },+ session_id=session_id,+ )+ pre_click_checked = state_res.get('result', {}).get('value')+ self.logger.debug(f'Checkbox pre-click state: checked={pre_click_checked}')+ except Exception as e:+ self.logger.debug(f'Could not capture pre-click checkbox state: {e}')+# Get viewport dimensions for visibility checkslayout_metrics = await cdp_session.cdp_client.send.Page.getLayoutMetrics(session_id=session_id)viewport_width = layout_metrics['layoutViewport']['clientWidth']@@ -921,6 +947,43 @@ class DefaultActionWatchdog(BaseWatchdog):self.logger.debug('🖱️ Clicked successfully using x,y coordinates')+ # For checkbox/radio: verify state toggled, fall back to JS element.click() if not+ if is_toggle_element and pre_click_checked is not None and checkbox_object_id:+ try:+ await asyncio.sleep(0.05)+ state_res = await cdp_session.cdp_client.send.Runtime.callFunctionOn(+ params={+ 'functionDeclaration': 'function() { return this.checked; }',+ 'objectId': checkbox_object_id,+ 'returnByValue': True,+ },+ session_id=session_id,+ )+ post_click_checked = state_res.get('result', {}).get('value')+ if post_click_checked == pre_click_checked:+ # CDP mouse events didn't toggle the checkbox — try JS element.click()+ self.logger.debug(+ f'Checkbox state unchanged after CDP click (checked={pre_click_checked}), using JS fallback'+ )+ await cdp_session.cdp_client.send.Runtime.callFunctionOn(+ params={'functionDeclaration': 'function() { this.click(); }', 'objectId': checkbox_object_id},+ session_id=session_id,+ )+ await asyncio.sleep(0.05)+ final_res = await cdp_session.cdp_client.send.Runtime.callFunctionOn(+ params={+ 'functionDeclaration': 'function() { return this.checked; }',+ 'objectId': checkbox_object_id,+ 'returnByValue': True,+ },+ session_id=session_id,+ )+ post_click_checked = final_res.get('result', {}).get('value')+ self.logger.debug(f'Checkbox post-click state: checked={post_click_checked}')+ return {'click_x': center_x, 'click_y': center_y, 'checked': post_click_checked}+ except Exception as e:+ self.logger.debug(f'Checkbox state verification failed (non-critical): {e}')+# Return coordinates as dict for metadatareturn {'click_x': center_x, 'click_y': center_y}diff --git a/browser_use/tools/service.py b/browser_use/tools/service.pyindex 5e0a40b30..baaa5f69f 100644--- a/browser_use/tools/service.py+++ b/browser_use/tools/service.py@@ -520,9 +520,7 @@ class Tools(Generic[Context]):browser_session: BrowserSession,tabs_before: set[str],) -> str:- """Detect if a click opened a new tab, and return a note for the agent.- Waits briefly for CDP events to propagate, then checks if any new tabs appeared.- """+ """Detect if a click opened a new tab and automatically switch to it."""try:# Brief delay to allow CDP Target.attachedToTarget events to propagate# and be processed by SessionManager._handle_target_attached@@ -531,8 +529,16 @@ class Tools(Generic[Context]):tabs_after = await browser_session.get_tabs()new_tabs = [t for t in tabs_after if t.target_id not in tabs_before]if new_tabs:- new_tab_id = new_tabs[0].target_id[-4:]- return f'. Note: This opened a new tab (tab_id: {new_tab_id}) - switch to it if you need to interact with the new page.'+ new_tab = new_tabs[0]+ new_tab_id = new_tab.target_id[-4:]+ # Auto-switch to the new tab so the agent can immediately interact with it+ try:+ switch_event = browser_session.event_bus.dispatch(SwitchTabEvent(target_id=new_tab.target_id))+ await switch_event+ await switch_event.event_result(raise_if_any=False, raise_if_none=False)+ return f'. Automatically switched to new tab (tab_id: {new_tab_id}).'+ except Exception:+ return f'. Note: This opened a new tab (tab_id: {new_tab_id}) - switch to it if you need to interact with the new page.'except Exception:passreturn ''