Skip to content

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

add support for close_tab action

Nick Sweeting85fc7c7e906a
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 3101f87a8..127fd3468 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -16,6 +16,7 @@ from browser_use.browser.context import BrowserContext
from browser_use.controller.registry.service import Registry
from browser_use.controller.views import (
ClickElementAction,
+ CloseTabAction,
DoneAction,
GoToUrlAction,
GroupTabsAction,
@@ -202,6 +203,16 @@ class Controller(Generic[Context]):
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
+ @self.registry.action('Close an existing tab', param_model=CloseTabAction)
+ async def close_tab(params: CloseTabAction, browser: BrowserContext):
+ await browser.switch_to_tab(params.page_id)
+ page = await browser.get_current_page()
+ url = page.url
+ await page.close()
+ msg = f'❌ Closed tab #{params.page_id} with url {url}'
+ logger.info(msg)
+ return ActionResult(extracted_content=msg, include_in_memory=True)
+
# Content Actions
@self.registry.action(
'Extract page content to retrieve specific information from the page, e.g. all company names, a specifc description, all information about, links with companies in structured format or simply links',
diff --git a/browser_use/controller/views.py b/browser_use/controller/views.py
index 853612db6..a9a43ec87 100644
--- a/browser_use/controller/views.py
+++ b/browser_use/controller/views.py
@@ -36,6 +36,10 @@ class OpenTabAction(BaseModel):
url: str
+class CloseTabAction(BaseModel):
+ page_id: int
+
+
class ScrollAction(BaseModel):
amount: Optional[int] = None # The number of pixels to scroll. If None, scroll down/up one page