Skip to content

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

fix: Binding already registered issue on follow-up task

2pac6a5b6ead1ba5
diff --git a/browser_use/browser/session.py b/browser_use/browser/session.py
index 2497460e7..1f9aa35aa 100644
--- a/browser_use/browser/session.py
+++ b/browser_use/browser/session.py
@@ -536,7 +536,19 @@ class BrowserSession(BaseModel):
f'(agent will stay on [{agent_tab_idx}]{_log_pretty_url(agent_url)})'
)
- await self.browser_context.expose_binding('_BrowserUseonTabVisibilityChange', _BrowserUseonTabVisibilityChange)
+ try:
+ await self.browser_context.expose_binding('_BrowserUseonTabVisibilityChange', _BrowserUseonTabVisibilityChange)
+
+ except Exception as e:
+ if 'Function "_BrowserUseonTabVisibilityChange" has been already registered' in str(e):
+ logger.debug(
+ '⚠️ Function "_BrowserUseonTabVisibilityChange" has been already registered, '
+ 'this is likely because the browser was already started with an existing BrowserSession()'
+ )
+
+ else:
+ raise e
+
update_tab_focus_script = """
// --- Method 1: visibilitychange event (unfortunately *all* tabs are always marked visible by playwright, usually does not fire) ---
document.addEventListener('visibilitychange', async () => {
diff --git a/examples/features/multiple_tasks.py b/examples/features/multiple_tasks.py
new file mode 100644
index 000000000..c6c0f0b15
--- /dev/null
+++ b/examples/features/multiple_tasks.py
@@ -0,0 +1,81 @@
+import asyncio
+import os
+import sys
+
+
+sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
+
+from dotenv import load_dotenv
+
+load_dotenv()
+
+from playwright.async_api import async_playwright
+from langchain_google_genai import ChatGoogleGenerativeAI
+from pydantic import SecretStr
+
+from browser_use import Agent
+from browser_use.browser import BrowserSession
+
+api_key = os.getenv('GOOGLE_API_KEY')
+
+if not api_key:
+ raise ValueError('GOOGLE_API_KEY is not set')
+
+llm = ChatGoogleGenerativeAI(model='gemini-2.0-flash', api_key=SecretStr(api_key))
+
+async def main():
+ async with async_playwright() as p:
+ try:
+ browser = await p.chromium.launch(
+ headless=False,
+ )
+
+ context = await browser.new_context(
+ viewport={"width": 1502, "height": 853},
+ ignore_https_errors=True,
+ )
+
+ agent = Agent(
+ browser_session=BrowserSession(
+ browser_context=context,
+ ),
+ task="Go to https://browser-use.com/",
+ llm=llm,
+ )
+
+ result = await agent.run()
+ print(f"First task was {'successful' if result.is_successful else 'not successful'}")
+
+ if not result.is_successful:
+ raise RuntimeError("Failed to navigate to the initial page.")
+
+ agent.add_new_task("Navigate to the documenation page")
+
+ result = await agent.run()
+ print(f"Second task was {'successful' if result.is_successful else 'not successful'}")
+
+ if not result.is_successful:
+ raise RuntimeError("Failed to navigate to the documentation page.")
+
+ while True:
+ next_task = input("Write your next task or leave empty to exit\n> ")
+
+ if not next_task.strip():
+ print("Exiting...")
+ break
+
+ agent.add_new_task(next_task)
+ result = await agent.run()
+
+ print(f"Task '{next_task}' was {'successful' if result.is_successful else 'not successful'}")
+
+ if not result.is_successful:
+ print("Failed to complete the task. Please try again.")
+ continue
+
+ finally:
+ await context.close()
+ await browser.close()
+
+if __name__ == '__main__':
+ asyncio.run(main())