Skip to content

Stealth browser automation for AI agents over MCP and the Chrome DevTools Protocol: navigation, network hooks, DOM extraction, and pixel-accurate UI cloning.

feat(cdp): expose Page-domain commands via dedicated tool + generalized executor

Jakepawlaad0b44b7955
diff --git a/src/cdp_function_executor.py b/src/cdp_function_executor.py
index b112dee..87b4609 100644
--- a/src/cdp_function_executor.py
+++ b/src/cdp_function_executor.py
@@ -102,37 +102,63 @@ class CDPFunctionExecutor:
async def list_cdp_commands(self) -> List[str]:
"""
- Lists all available CDP Runtime commands.
+ Lists CDP commands the generic executor will accept.
+
+ Includes core Runtime methods plus a curated set of Page-domain
+ methods (notably addScriptToEvaluateOnNewDocument) that are useful
+ for pre-page-script API spoofing (WebGL renderer, navigator props).
Returns:
List[str]: List of command names.
"""
commands = [
+ # Runtime domain
"evaluate", "callFunctionOn", "addBinding", "removeBinding",
"compileScript", "runScript", "awaitPromise", "getProperties",
"getExceptionDetails", "globalLexicalScopeNames", "queryObjects",
"releaseObject", "releaseObjectGroup", "terminateExecution",
"setAsyncCallStackDepth", "setCustomObjectFormatterEnabled",
"setMaxCallStackSizeToCapture", "runIfWaitingForDebugger",
- "discardConsoleEntries", "getHeapUsage", "getIsolateId"
+ "discardConsoleEntries", "getHeapUsage", "getIsolateId",
+ # Page domain (resolved from uc.cdp.page when not found on Runtime)
+ "addScriptToEvaluateOnNewDocument",
+ "removeScriptToEvaluateOnNewDocument",
+ "reload", "navigate", "stopLoading", "getFrameTree",
+ "setBypassCSP", "setDocumentContent",
]
return commands
+ def _resolve_cdp_method(self, command: str):
+ """
+ Resolve a CDP command name across Runtime and Page domains.
+
+ nodriver exposes each CDP domain as a submodule under uc.cdp (e.g.
+ uc.cdp.runtime, uc.cdp.page). Method names are snake_cased on the
+ Python side but the wire uses camelCase. We accept either.
+ """
+ snake = "".join(["_" + c.lower() if c.isupper() else c for c in command]).lstrip("_")
+ for domain in (uc.cdp.runtime, uc.cdp.page):
+ for name in (command, snake):
+ method = getattr(domain, name, None)
+ if callable(method):
+ return method
+ return None
+
async def execute_cdp_command(self, tab: Tab, command: str, params: Dict[str, Any]) -> Dict[str, Any]:
"""
- Executes any CDP Runtime command with given parameters.
+ Executes a CDP command (Runtime or Page domain) with given parameters.
Args:
tab (Tab): The browser tab.
- command (str): CDP command name.
- params (Dict[str, Any]): Parameters for the command.
+ command (str): CDP command name (camelCase or snake_case).
+ params (Dict[str, Any]): Parameters for the command (snake_case keys).
Returns:
Dict[str, Any]: Result of the command execution.
"""
try:
await self.enable_runtime(tab)
- cdp_method = getattr(uc.cdp.runtime, command, None)
+ cdp_method = self._resolve_cdp_method(command)
if not cdp_method:
raise ValueError(f"Unknown CDP command: {command}")
result = await tab.send(cdp_method(**params))
diff --git a/src/server.py b/src/server.py
index 478830f..2c7a52d 100644
--- a/src/server.py
+++ b/src/server.py
@@ -2323,6 +2323,52 @@ async def execute_cdp_command(
return await cdp_function_executor.execute_cdp_command(tab, command, params or {})
+@section_tool("cdp-functions")
+async def add_script_to_evaluate_on_new_document(
+ instance_id: str,
+ source: str,
+ run_immediately: bool = True,
+) -> Dict[str, Any]:
+ """
+ Install a JavaScript snippet that runs on EVERY new document/frame BEFORE
+ any page script executes. Use this to spoof browser APIs (WebGL renderer,
+ navigator props, etc.) so values are already overridden when bot-detection
+ pages query them inline at parse time.
+
+ Wraps CDP Page.addScriptToEvaluateOnNewDocument. Auto-enables Page domain
+ first (without that, the addScript silently no-ops on a fresh tab).
+
+ Args:
+ instance_id (str): Browser instance ID.
+ source (str): JavaScript source. Runs in the page's main world before
+ any other script on every navigation, including iframes.
+ run_immediately (bool): If True (default), the script also runs on the
+ current document if one is already loaded. Useful when
+ the tab is at about:blank and you want the spoof active
+ before any user navigation.
+
+ Returns:
+ Dict[str, Any]: { success, identifier } where identifier can be passed
+ to Page.removeScriptToEvaluateOnNewDocument later.
+ """
+ import nodriver as uc
+ tab = await browser_manager.get_tab(instance_id)
+ if not tab:
+ return {"success": False, "error": f"Instance not found: {instance_id}"}
+ try:
+ # CRITICAL: Page domain must be enabled before addScript will take effect.
+ # nodriver does not auto-enable it for ad-hoc Page method calls.
+ await tab.send(uc.cdp.page.enable())
+ result = await tab.send(uc.cdp.page.add_script_to_evaluate_on_new_document(
+ source=source,
+ run_immediately=run_immediately,
+ ))
+ identifier = getattr(result, "identifier", None) or (result if isinstance(result, str) else None)
+ return {"success": True, "identifier": identifier}
+ except Exception as e:
+ return {"success": False, "error": str(e)}
+
+
@section_tool("cdp-functions")
async def get_execution_contexts(
instance_id: str