Skip to content

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

Merge pull request #932 from Jonathanqjs/fix-element-addEventListener-detection

Nick Sweeting268fb8c259ce
diff --cc browser_use/browser/context.py
index 9ae75e618,7b2c5c206..aa16a9a2c
--- a/browser_use/browser/context.py
+++ b/browser_use/browser/context.py
@@@ -149,19 -133,63 +149,68 @@@ class BrowserContextConfig(BaseModel)
allowed_domains: list[str] | None = None
include_dynamic_attributes: bool = True
- _force_keep_context_alive: bool = False
+ keep_alive: bool = Field(default=False, alias='_force_keep_context_alive') # used to be called _force_keep_context_alive
+ is_mobile: bool | None = None
+ has_touch: bool | None = None
+ geolocation: dict | None = None
+ permissions: list[str] | None = None
+ timezone_id: str | None = None
- @dataclass
class BrowserSession:
- context: PlaywrightBrowserContext
- cached_state: BrowserState | None
-
+
+ def __init__(
+ self,
+ context: PlaywrightBrowserContext,
+ cached_state: BrowserState | None=None
+ ):
+ init_script = """
+ (() => {
+ if (!window.getEventListeners) {
+ window.getEventListeners = function (node) {
+ return node.__listeners || {};
+ };
+
+ // Save the original addEventListener
+ const originalAddEventListener = Element.prototype.addEventListener;
+
+ const eventProxy = {
+ addEventListener: function (type, listener, options = {}) {
+ // Initialize __listeners if not exists
+ const defaultOptions = { once: false, passive: false, capture: false };
+ if(typeof options === 'boolean') {
+ options = { capture: options };
+ }
+ options = { ...defaultOptions, ...options };
+ if (!this.__listeners) {
+ this.__listeners = {};
+ }
+
+ // Initialize array for this event type if not exists
+ if (!this.__listeners[type]) {
+ this.__listeners[type] = [];
+ }
+
+
+ // Add the listener to __listeners
+ this.__listeners[type].push({
+ listener: listener,
+ type: type,
+ ...options
+ });
+
+ // Call original addEventListener using the saved reference
+ return originalAddEventListener.call(this, type, listener, options);
+ }
+ };
+
+ Element.prototype.addEventListener = eventProxy.addEventListener;
+ }
+ })()
+ """
+ self.context = context
+ self.cached_state = cached_state
+ self.context.on('page', lambda page: page.add_init_script(init_script))
@dataclass
class BrowserContextState: