Skip to content

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

also save storage_state in save_cookies

Nick Sweeting191544705e77
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index a7ba61151..a4dc11171 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -1042,16 +1042,22 @@ class BrowserSession(BaseModel):
Save cookies to the specified path or the default cookies_file in the downloads_dir.
"""
if self.browser_context:
+ # old deprecated cookies_file method:
cookies = await self.browser_context.cookies()
out_path = path or self.browser_profile.cookies_file
if out_path:
# If out_path is not absolute, resolve relative to downloads_dir
out_path = Path(out_path)
if not out_path.is_absolute():
- out_path = Path(self.browser_profile.downloads_dir) / out_path
+ out_path = Path(self.browser_profile.downloads_dir or '.') / out_path
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(cookies, indent=4)) # TODO: replace with anyio asyncio or anyio write
+ # new recommended storage_state method:
+ storage_state = await self.browser_context.storage_state()
+ storage_state_path = Path(self.browser_profile.downloads_dir or '.') / 'storage_state.json'
+ storage_state_path.write_text(json.dumps(storage_state, indent=4))
+
async def load_cookies_from_file(self) -> None:
"""
Load cookies from the cookies_file if it exists and apply them to the browser context.