Skip to content

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

Draft tab switching

magmueller4c08bf8d45f3
diff --git a/src/agent/prompts.py b/src/agent/prompts.py
index 612b81682..4230fef81 100644
--- a/src/agent/prompts.py
+++ b/src/agent/prompts.py
@@ -68,6 +68,8 @@ class AgentMessagePrompt:
def get_user_message(self) -> HumanMessage:
state_description = f"""
Current url: {self.state.url}
+Available tabs:
+{self.state.tabs}
Interactive elements:
{self.state.dom_items_to_string()}
"""
diff --git a/src/agent/service.py b/src/agent/service.py
index e81704bf6..4619b3ccf 100644
--- a/src/agent/service.py
+++ b/src/agent/service.py
@@ -86,7 +86,7 @@ class AgentService:
# TODO: include state, actions, etc.
new_message = AgentMessagePrompt(state).get_user_message()
-
+ print(f'current tabs: {state.tabs}')
input_messages = self.messages + [new_message]
# if self.use_vision:
# print(f'model input content with image: {new_message.content[0]}')
diff --git a/src/browser/service.py b/src/browser/service.py
index 7f2f38fb2..d775fd244 100644
--- a/src/browser/service.py
+++ b/src/browser/service.py
@@ -31,6 +31,8 @@ class BrowserService:
self._ob = Screenshot.Screenshot()
self.MINIMUM_WAIT_TIME = 0.5
self.MAXIMUM_WAIT_TIME = 5
+ self._current_handle = None # Track current handle
+ self._tab_cache = {} # Cache tab info
def init(self) -> webdriver.Chrome:
"""
@@ -320,7 +322,84 @@ class BrowserService:
if index not in state.selector_map:
raise Exception(f'Element index {index} not found in selector map')
+ # Store current number of tabs before clicking
+ driver = self._get_driver()
+ initial_handles = len(driver.window_handles)
+
xpath = state.selector_map[index]
self._click_element_by_xpath(xpath)
+ # Check if new tab was opened
+ current_handles = len(driver.window_handles)
+ if current_handles > initial_handles:
+ return self.handle_new_tab()
+
# endregion
+
+ def handle_new_tab(self) -> dict:
+ """Get info about newly opened tab without switching"""
+ driver = self._get_driver()
+ handles = driver.window_handles
+ new_handle = handles[-1]
+
+ # Only switch if we need to get info about the new tab
+ current_handle = driver.current_window_handle
+ driver.switch_to.window(new_handle)
+
+ tab_info = {
+ 'handle': new_handle,
+ 'url': driver.current_url,
+ 'title': driver.title,
+ }
+
+ # Cache the info
+ self._tab_cache[new_handle] = tab_info
+
+ # Switch back
+ driver.switch_to.window(current_handle)
+ return tab_info
+
+ def get_tabs_info(self) -> list[dict]:
+ """Get cached information about all tabs"""
+ driver = self._get_driver()
+ current_handle = driver.current_window_handle
+
+ # Update cache for current tab
+ self._tab_cache[current_handle] = {
+ 'handle': current_handle,
+ 'url': driver.current_url,
+ 'title': driver.title,
+ 'is_current': True,
+ }
+
+ # Return all cached tab info
+ return [
+ {**tab_info, 'is_current': handle == current_handle}
+ for handle, tab_info in self._tab_cache.items()
+ if handle in driver.window_handles # Only return existing tabs
+ ]
+
+ def switch_tab(self, handle: str) -> dict:
+ """Switch to specified tab and return its info"""
+ driver = self._get_driver()
+
+ # Verify handle exists
+ if handle not in driver.window_handles:
+ raise ValueError(f'Tab handle {handle} not found')
+
+ # Only switch if we're not already on that tab
+ current_handle = driver.current_window_handle
+ if handle != current_handle:
+ driver.switch_to.window(handle)
+ # Wait for tab to be ready
+ self.wait_for_page_load()
+
+ # Update and return tab info
+ tab_info = {
+ 'handle': handle,
+ 'url': driver.current_url,
+ 'title': driver.title,
+ 'is_current': True,
+ }
+ self._tab_cache[handle] = tab_info
+ return tab_info
diff --git a/src/controller/service.py b/src/controller/service.py
index 1f069a2b1..c13860034 100644
--- a/src/controller/service.py
+++ b/src/controller/service.py
@@ -31,6 +31,10 @@ class ControllerService:
def get_current_state(self, screenshot: bool = False) -> ControllerPageState:
browser_state = self.get_cached_browser_state(force_update=True)
+
+ # Get tab information without switching
+ tabs = self.browser.get_tabs_info()
+
screenshot_b64 = None
if screenshot:
screenshot_b64 = self.browser.take_screenshot()
@@ -41,6 +45,7 @@ class ControllerService:
title=browser_state.title,
selector_map=browser_state.selector_map,
screenshot=screenshot_b64,
+ tabs=tabs,
)
@time_execution_sync('--act')
@@ -50,6 +55,8 @@ class ControllerService:
if action.search_google:
self.browser.search_google(action.search_google.query)
+ elif action.switch_tab:
+ self.browser.switch_tab(action.switch_tab.handle)
elif action.go_to_url:
self.browser.go_to_url(action.go_to_url.url)
elif action.nothing:
@@ -76,4 +83,4 @@ class ControllerService:
return ControllerActionResult(done=False)
except Exception as e:
- return ControllerActionResult(done=False, error=str(e))
+ return ControllerActionResult(done=False, error=f'Error executing action: {str(e)}')
diff --git a/src/controller/views.py b/src/controller/views.py
index 5f9425530..b4f467eaa 100644
--- a/src/controller/views.py
+++ b/src/controller/views.py
@@ -26,6 +26,10 @@ class DoneControllerAction(BaseModel):
text: str
+class SwitchTabControllerAction(BaseModel):
+ handle: str # The window handle to switch to
+
+
class ControllerActions(BaseModel):
"""
Controller actions you can use to interact.
@@ -39,6 +43,7 @@ class ControllerActions(BaseModel):
click_element: Optional[ClickElementControllerAction] = None
input_text: Optional[InputTextControllerAction] = None
extract_page_content: Optional[Literal[True]] = None
+ switch_tab: Optional[SwitchTabControllerAction] = None # New action
@staticmethod
def description() -> str:
@@ -62,6 +67,8 @@ class ControllerActions(BaseModel):
Example: {"input_text": {"id": 1, "text": "Hello world"}}
- Get the page content in markdown
Example: {"extract_page_content": true}
+- Switch to a different browser tab
+ Example: {"switch_tab": {"handle": "CDwindow-1234..."}}
"""
@@ -73,3 +80,13 @@ class ControllerActionResult(BaseModel):
class ControllerPageState(BrowserState):
screenshot: Optional[str] = None
+ tabs: list[dict] = [] # Add tabs info to state
+
+ def model_dump(self) -> dict:
+ dump = super().model_dump()
+ # Add a summary of available tabs
+ if self.tabs:
+ dump['available_tabs'] = [
+ f"Tab {i+1}: {tab['title']} ({tab['url']})" for i, tab in enumerate(self.tabs)
+ ]
+ return dump