Skip to content

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

Error handling for restricted domains

magmuellere7c49bfcac26
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.py
index de75466f0..e75e81f18 100644
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@ -23,7 +23,7 @@ from playwright.async_api import (
Page,
)
-from browser_use.browser.views import BrowserError, BrowserState, TabInfo
+from browser_use.browser.views import BrowserError, BrowserState, TabInfo, URLNotAllowedError
from browser_use.dom.service import DomService
from browser_use.dom.views import DOMElementNode, SelectorMap
from browser_use.utils import time_execution_sync
@@ -495,7 +495,8 @@ class BrowserContext:
# Check if the loaded URL is allowed
page = await self.get_current_page()
await self._check_and_handle_navigation(page)
-
+ except URLNotAllowedError as e:
+ raise e
except Exception:
logger.warning('Page load failed, continuing...')
pass
@@ -539,10 +540,10 @@ class BrowserContext:
if not self._is_url_allowed(page.url):
logger.warning(f'Navigation to non-allowed URL detected: {page.url}')
try:
- await page.go_back()
+ await self.go_back()
except Exception as e:
logger.error(f'Failed to go back after detecting non-allowed URL: {str(e)}')
- raise BrowserError(f'Navigation to non-allowed URL: {page.url}')
+ raise URLNotAllowedError(f'Navigation to non-allowed URL: {page.url}')
async def navigate_to(self, url: str):
"""Navigate to a URL"""
@@ -562,8 +563,13 @@ class BrowserContext:
async def go_back(self):
"""Navigate back in history"""
page = await self.get_current_page()
- await page.go_back()
- await page.wait_for_load_state()
+ try:
+ # Add timeout and catch any timeout errors
+ await page.go_back(timeout=5000, wait_until='domcontentloaded')
+ await self._wait_for_page_and_frames_load(timeout_overwrite=1.0)
+ except Exception as e:
+ logger.warning(f'Error during go_back: {e}')
+ # Continue even if there's an error since the navigation might have succeeded
async def go_forward(self):
"""Navigate forward in history"""
@@ -938,15 +944,21 @@ class BrowserContext:
await page.wait_for_load_state()
# Check if navigation occurred and if the new URL is allowed
await self._check_and_handle_navigation(page)
+ except URLNotAllowedError as e:
+ raise e
except Exception:
try:
await page.evaluate('(el) => el.click()', element)
await page.wait_for_load_state()
# Check if navigation occurred and if the new URL is allowed
await self._check_and_handle_navigation(page)
+ except URLNotAllowedError as e:
+ raise e
except Exception as e:
raise Exception(f'Failed to click element: {str(e)}')
+ except URLNotAllowedError as e:
+ raise e
except Exception as e:
raise Exception(f'Failed to click element: {repr(element_node)}. Error: {str(e)}')
diff --git a/browser_use/browser/views.py b/browser_use/browser/views.py
index c0cf9f7a1..3434d86e2 100644
--- a/browser_use/browser/views.py
+++ b/browser_use/browser/views.py
@@ -47,3 +47,7 @@ class BrowserStateHistory:
class BrowserError(Exception):
"""Base class for all browser errors"""
+
+
+class URLNotAllowedError(BrowserError):
+ """Error raised when a URL is not allowed"""
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index a1eeeccc2..c925f5f30 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -62,9 +62,7 @@ class Controller:
@self.registry.action('Go back', requires_browser=True)
async def go_back(browser: BrowserContext):
- page = await browser.get_current_page()
- await page.go_back()
- await page.wait_for_load_state()
+ await browser.go_back()
msg = '🔙 Navigated back'
logger.info(msg)
return ActionResult(extracted_content=msg, include_in_memory=True)
@@ -102,7 +100,7 @@ class Controller:
await browser.switch_to_tab(-1)
return ActionResult(extracted_content=msg, include_in_memory=True)
except Exception as e:
- logger.warning(f'Element no longer available with index {params.index} - most likely the page changed')
+ logger.warning(f'Element not clickable with index {params.index} - most likely the page changed')
return ActionResult(error=str(e))
@self.registry.action(
diff --git a/examples/restrict_urls.py b/examples/restrict_urls.py
index 0ad7e23e2..398c78559 100644
--- a/examples/restrict_urls.py
+++ b/examples/restrict_urls.py
@@ -15,7 +15,9 @@ from browser_use.browser.browser import Browser, BrowserConfig
from browser_use.controller.service import Controller
llm = ChatOpenAI(model='gpt-4o', temperature=0.0)
-task = 'go to google.com and search for openai.com and click on the first link'
+task = (
+ 'go to google.com and search for openai.com and click on the first link then extract content and scroll down - whats there?'
+)
allowed_domains = ['google.com']