execute_script
Execute JavaScript in the active browser page and return a JSON-serializable result. Useful for scraping dynamic content, manipulating page state, or testing scripts directly.
Instructions
Execute JavaScript in the active page and return the JSON-serializable result.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| script | Yes | ||
| args | No |
Output Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||
Implementation Reference
- src/selenium_mcp_server/server.py:171-174 (registration)The tool 'execute_script' is registered as an MCP tool via the @mcp.tool() decorator. It accepts a 'script' string and optional 'args' list, delegates to browser.execute_script via the _run helper.
@mcp.tool() def execute_script(script: str, args: list[Any] | None = None) -> dict[str, Any]: """Execute JavaScript in the active page and return the JSON-serializable result.""" return _run("execute_script", browser.execute_script, script, args) - The _run helper function wraps calls to browser methods with exception handling and conversion via _as_dict.
def _run(action: str, func: Any, *args: Any, **kwargs: Any) -> Any: try: return _as_dict(func(*args, **kwargs)) except BrowserError: logger.exception("Browser action failed: %s", action) raise except Exception as exc: logger.exception("Unexpected Selenium MCP error during %s", action) raise BrowserError(f"{action} failed: {exc}") from exc - The actual implementation of execute_script in BrowserManager. It acquires the lock, calls Selenium's driver.execute_script(script, *args), and returns the result.
def execute_script(self, script: str, args: list[Any] | None = None) -> dict[str, Any]: with self._lock: result = self._require_driver().execute_script(script, *(args or [])) return {"result": result}