Skip to content

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

Add profile copying to BrowserProfile class

kalil0321481b1b5f4576
diff --git a/browser_use/browser/profile.py b/browser_use/browser/profile.py
index 53ffed993..8405955d4 100644
--- a/browser_use/browser/profile.py
+++ b/browser_use/browser/profile.py
@@ -773,6 +773,33 @@ class BrowserProfile(BrowserConnectArgs, BrowserLaunchPersistentContextArgs, Bro
def model_post_init(self, __context: Any) -> None:
"""Called after model initialization to set up display configuration."""
self.detect_display_configuration()
+ self._copy_profile()
+
+ def _copy_profile(self) -> None:
+ """Copy profile to temp directory if user_data_dir is not None and not already a temp dir."""
+ if self.user_data_dir is None:
+ return
+
+ user_data_str = str(self.user_data_dir)
+ if 'browser-use-user-data-dir-' in user_data_str.lower():
+ # Already using a temp directory, no need to copy
+ return
+
+ temp_dir = tempfile.mkdtemp(prefix='browser-use-user-data-dir-')
+ path_original_profile = Path(self.user_data_dir) / self.profile_directory
+ path_temp_profile = Path(temp_dir) / self.profile_directory
+
+ if path_original_profile.exists():
+ import shutil
+
+ shutil.copytree(path_original_profile, path_temp_profile)
+ logger.info(f'Copied profile ({self.profile_directory}) to temp directory: {temp_dir}')
+ else:
+ Path(temp_dir).mkdir(parents=True, exist_ok=True)
+ path_temp_profile.mkdir(parents=True, exist_ok=True)
+ logger.info(f'Created new profile ({self.profile_directory}) in temp directory: {temp_dir}')
+
+ self.user_data_dir = temp_dir
def get_args(self) -> list[str]:
"""Get the list of all Chrome CLI launch args for this profile (compiled from defaults, user-provided, and system-specific)."""