Skip to content

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

feat(cli): add cookies command for get/set/clear operations

ShawnPana45d244e01ca2
diff --git a/browser_use/browser/events.py b/browser_use/browser/events.py
index 4c40cb428..d360058b6 100644
--- a/browser_use/browser/events.py
+++ b/browser_use/browser/events.py
@@ -471,6 +471,42 @@ class BrowserErrorEvent(BaseEvent):
event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_BrowserErrorEvent', 30.0)) # seconds
+# ============================================================================
+# Cookie Events
+# ============================================================================
+
+
+class GetCookiesEvent(BaseEvent[list[dict]]):
+ """Get browser cookies."""
+
+ url: str | None = None # Optional: filter by URL
+
+ event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_GetCookiesEvent', 15.0))
+
+
+class SetCookieEvent(BaseEvent[bool]):
+ """Set a browser cookie."""
+
+ name: str
+ value: str
+ domain: str | None = None
+ path: str = '/'
+ secure: bool = False
+ http_only: bool = False
+ same_site: Literal['Strict', 'Lax', 'None'] | None = None
+ expires: float | None = None # Unix timestamp
+
+ event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_SetCookieEvent', 15.0))
+
+
+class ClearCookiesEvent(BaseEvent[None]):
+ """Clear browser cookies."""
+
+ url: str | None = None # Optional: clear only cookies for this URL
+
+ event_timeout: float | None = Field(default_factory=lambda: _get_timeout('TIMEOUT_ClearCookiesEvent', 15.0))
+
+
# ============================================================================
# Storage State Events
# ============================================================================
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 7977cf517..f79901d2f 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -1480,6 +1480,13 @@ class BrowserSession(BaseModel):
self._recording_watchdog = RecordingWatchdog(event_bus=self.event_bus, browser_session=self)
self._recording_watchdog.attach_to_session()
+ # Initialize CookiesWatchdog (handles cookie get/set/clear operations)
+ from browser_use.browser.watchdogs.cookies_watchdog import CookiesWatchdog
+
+ CookiesWatchdog.model_rebuild()
+ self._cookies_watchdog = CookiesWatchdog(event_bus=self.event_bus, browser_session=self)
+ self._cookies_watchdog.attach_to_session()
+
# Mark watchdogs as attached to prevent duplicate attachment
self._watchdogs_attached = True
diff --git a/browser_use/browser/watchdogs/cookies_watchdog.py b/browser_use/browser/watchdogs/cookies_watchdog.py
new file mode 100644
index 000000000..e5139bbbc
--- /dev/null
+++ b/browser_use/browser/watchdogs/cookies_watchdog.py
@@ -0,0 +1,136 @@
+"""Cookies watchdog for direct cookie manipulation."""
+
+from typing import Any, ClassVar
+
+from bubus import BaseEvent
+from cdp_use.cdp.network import Cookie
+
+from browser_use.browser.events import (
+ ClearCookiesEvent,
+ GetCookiesEvent,
+ SetCookieEvent,
+)
+from browser_use.browser.watchdog_base import BaseWatchdog
+
+
+class CookiesWatchdog(BaseWatchdog):
+ """Handles direct cookie get/set/clear operations."""
+
+ LISTENS_TO: ClassVar[list[type[BaseEvent]]] = [
+ GetCookiesEvent,
+ SetCookieEvent,
+ ClearCookiesEvent,
+ ]
+ EMITS: ClassVar[list[type[BaseEvent]]] = []
+
+ async def on_GetCookiesEvent(self, event: GetCookiesEvent) -> list[dict[str, Any]]:
+ """Get browser cookies, optionally filtered by URL."""
+ try:
+ cookies = await self.browser_session._cdp_get_cookies()
+ # Convert Cookie objects to dicts for the result
+ cookie_list: list[dict[str, Any]] = []
+ for c in cookies:
+ cookie_dict: dict[str, Any] = {
+ 'name': c.get('name', ''),
+ 'value': c.get('value', ''),
+ 'domain': c.get('domain', ''),
+ 'path': c.get('path', '/'),
+ 'secure': c.get('secure', False),
+ 'httpOnly': c.get('httpOnly', False),
+ }
+ if 'sameSite' in c:
+ cookie_dict['sameSite'] = c.get('sameSite')
+ if 'expires' in c:
+ cookie_dict['expires'] = c.get('expires')
+ cookie_list.append(cookie_dict)
+
+ # Filter by URL if provided
+ if event.url:
+ from urllib.parse import urlparse
+
+ parsed = urlparse(event.url)
+ domain = parsed.netloc
+ # Filter cookies that match the domain
+ cookie_list = [
+ c for c in cookie_list
+ if domain.endswith(str(c.get('domain', '')).lstrip('.'))
+ or str(c.get('domain', '')).lstrip('.').endswith(domain)
+ ]
+
+ return cookie_list
+ except Exception as e:
+ self.logger.error(f'[CookiesWatchdog] Failed to get cookies: {e}')
+ return []
+
+ async def on_SetCookieEvent(self, event: SetCookieEvent) -> bool:
+ """Set a browser cookie."""
+ try:
+ cookie_dict: dict[str, Any] = {
+ 'name': event.name,
+ 'value': event.value,
+ 'path': event.path,
+ 'secure': event.secure,
+ 'httpOnly': event.http_only,
+ }
+
+ if event.domain:
+ cookie_dict['domain'] = event.domain
+ if event.same_site:
+ cookie_dict['sameSite'] = event.same_site
+ if event.expires:
+ cookie_dict['expires'] = event.expires
+
+ # If no domain specified, we need to get current URL's domain
+ if not event.domain:
+ cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=None)
+ if cdp_session:
+ # Get current URL to extract domain
+ result = await cdp_session.cdp_client.send.Runtime.evaluate(
+ params={'expression': 'window.location.hostname', 'returnByValue': True},
+ session_id=cdp_session.session_id,
+ )
+ hostname = result.get('result', {}).get('value', '')
+ if hostname:
+ cookie_dict['domain'] = hostname
+
+ # Convert dict to Cookie object
+ cookie_obj = Cookie(**cookie_dict)
+ await self.browser_session._cdp_set_cookies([cookie_obj])
+ self.logger.debug(f'[CookiesWatchdog] Set cookie: {event.name}')
+ return True
+ except Exception as e:
+ self.logger.error(f'[CookiesWatchdog] Failed to set cookie: {e}')
+ return False
+
+ async def on_ClearCookiesEvent(self, event: ClearCookiesEvent) -> None:
+ """Clear browser cookies."""
+ try:
+ if event.url:
+ # Clear cookies only for specific URL
+ # First get all cookies, then delete ones matching the URL
+ cookies = await self.browser_session._cdp_get_cookies()
+ from urllib.parse import urlparse
+
+ parsed = urlparse(event.url)
+ domain = parsed.netloc
+
+ cdp_session = await self.browser_session.get_or_create_cdp_session(target_id=None)
+ if cdp_session:
+ for cookie in cookies:
+ cookie_domain = str(cookie.get('domain', '')).lstrip('.')
+ if domain.endswith(cookie_domain) or cookie_domain.endswith(domain):
+ await cdp_session.cdp_client.send.Network.deleteCookies(
+ params={
+ 'name': cookie.get('name', ''),
+ 'domain': cookie.get('domain'),
+ 'path': cookie.get('path', '/'),
+ },
+ session_id=cdp_session.session_id,
+ )
+ else:
+ # Clear all cookies
+ await self.browser_session._cdp_clear_cookies()
+
+ self.logger.debug(f'[CookiesWatchdog] Cleared cookies' + (f' for {event.url}' if event.url else ''))
+ except Exception as e:
+ self.logger.error(f'[CookiesWatchdog] Failed to clear cookies: {e}')
diff --git a/browser_use/skill_cli/commands/browser.py b/browser_use/skill_cli/commands/browser.py
index 4e1f94dfc..9905a198b 100644
--- a/browser_use/skill_cli/commands/browser.py
+++ b/browser_use/skill_cli/commands/browser.py
@@ -24,6 +24,7 @@ COMMANDS = {
'select',
'eval',
'extract',
+ 'cookies',
}
@@ -190,4 +191,44 @@ async def handle(action: str, session: SessionInfo, params: dict[str, Any]) -> A
# For now, return a placeholder
return {'query': query, 'error': 'extract requires agent mode - use: browser-use run "extract ..."'}
+ elif action == 'cookies':
+ cookies_command = params.get('cookies_command')
+
+ if cookies_command == 'get':
+ from browser_use.browser.events import GetCookiesEvent
+
+ url = params.get('url')
+ event = GetCookiesEvent(url=url)
+ await bs.event_bus.dispatch(event)
+ cookies = await event.event_result()
+ return {'cookies': cookies}
+
+ elif cookies_command == 'set':
+ from browser_use.browser.events import SetCookieEvent
+
+ event = SetCookieEvent(
+ name=params['name'],
+ value=params['value'],
+ domain=params.get('domain'),
+ path=params.get('path', '/'),
+ secure=params.get('secure', False),
+ http_only=params.get('http_only', False),
+ same_site=params.get('same_site'),
+ expires=params.get('expires'),
+ )
+ await bs.event_bus.dispatch(event)
+ success = await event.event_result()
+ return {'set': params['name'], 'success': success}
+
+ elif cookies_command == 'clear':
+ from browser_use.browser.events import ClearCookiesEvent
+
+ url = params.get('url')
+ event = ClearCookiesEvent(url=url)
+ await bs.event_bus.dispatch(event)
+ # No event_result() call - this is a void operation
+ return {'cleared': True, 'url': url}
+
+ return {'error': 'Invalid cookies command. Use: get, set, clear'}
+
raise ValueError(f'Unknown browser action: {action}')
diff --git a/browser_use/skill_cli/main.py b/browser_use/skill_cli/main.py
index f6c69f71e..561c11706 100755
--- a/browser_use/skill_cli/main.py
+++ b/browser_use/skill_cli/main.py
@@ -264,6 +264,32 @@ Examples:
p = subparsers.add_parser('extract', help='Extract data using LLM')
p.add_argument('query', help='What to extract')
+ # -------------------------------------------------------------------------
+ # Cookies Commands
+ # -------------------------------------------------------------------------
+
+ cookies_p = subparsers.add_parser('cookies', help='Cookie operations')
+ cookies_sub = cookies_p.add_subparsers(dest='cookies_command')
+
+ # cookies get [--url URL]
+ p = cookies_sub.add_parser('get', help='Get all cookies')
+ p.add_argument('--url', help='Filter by URL')
+
+ # cookies set <name> <value>
+ p = cookies_sub.add_parser('set', help='Set a cookie')
+ p.add_argument('name', help='Cookie name')
+ p.add_argument('value', help='Cookie value')
+ p.add_argument('--domain', help='Cookie domain')
+ p.add_argument('--path', default='/', help='Cookie path')
+ p.add_argument('--secure', action='store_true', help='Secure cookie')
+ p.add_argument('--http-only', action='store_true', help='HTTP-only cookie')
+ p.add_argument('--same-site', choices=['Strict', 'Lax', 'None'], help='SameSite attribute')
+ p.add_argument('--expires', type=float, help='Expiration timestamp')
+
+ # cookies clear [--url URL]
+ p = cookies_sub.add_parser('clear', help='Clear cookies')
+ p.add_argument('--url', help='Clear only for URL')
+
# -------------------------------------------------------------------------
# Python Execution
# -------------------------------------------------------------------------
diff --git a/skills/browser-use/SKILL.md b/skills/browser-use/SKILL.md
index 70a00f196..a5d42d037 100644
--- a/skills/browser-use/SKILL.md
+++ b/skills/browser-use/SKILL.md
@@ -94,6 +94,16 @@ browser-use eval "document.title" # Execute JavaScript, return result
browser-use extract "all product prices" # Extract data using LLM (requires API key)
```
+### Cookies
+```bash
+browser-use cookies get # Get all cookies
+browser-use cookies get --url <url> # Get cookies for specific URL
+browser-use cookies set <name> <value> # Set a cookie
+browser-use cookies set name val --domain .example.com --secure --http-only
+browser-use cookies clear # Clear all cookies
+browser-use cookies clear --url <url> # Clear cookies for specific URL
+```
+
### Python Execution (Persistent Session)
```bash
browser-use python "x = 42" # Set variable