Execute JavaScript in the current window and return its result. Arguments and return values are converted as by ``execute_script``: ``WebElement`` arguments are passed to the page as elements, and elements in the result come back as ``WebElement``. Args:
(self, function_declaration: str | PinnedScript, *args: Any, context_id: str | None = None)
| 316 | self._script.unpin(script_id) |
| 317 | |
| 318 | def execute(self, function_declaration: str | PinnedScript, *args: Any, context_id: str | None = None) -> Any: |
| 319 | """Execute JavaScript in the current window and return its result. |
| 320 | |
| 321 | Arguments and return values are converted as by ``execute_script``: |
| 322 | ``WebElement`` arguments are passed to the page as elements, and |
| 323 | elements in the result come back as ``WebElement``. |
| 324 | |
| 325 | Args: |
| 326 | function_declaration: The function to run, e.g. ``"(a, b) => a + b"``, |
| 327 | or a ``PinnedScript`` returned by ``pin()``. |
| 328 | *args: Arguments passed to the function. When ``function_declaration`` is a |
| 329 | ``PinnedScript``, the single argument is the code to run with |
| 330 | the pinned source in scope, e.g. ``"return helper();"``. |
| 331 | context_id: The window handle to run in. Defaults to the current |
| 332 | window. |
| 333 | |
| 334 | Returns: |
| 335 | The function's return value. When ``function_declaration`` is a ``PinnedScript``, |
| 336 | a ``ScriptResult`` instead, which reports failures through |
| 337 | ``ScriptResult.error`` rather than raising. |
| 338 | |
| 339 | Raises: |
| 340 | JavascriptException: If the script throws. |
| 341 | |
| 342 | Example: |
| 343 | `total = driver.script.execute("(a, b) => a + b", 1, 2)` |
| 344 | """ |
| 345 | if isinstance(function_declaration, PinnedScript): |
| 346 | result = self._script.execute(function_declaration, *args, context_id=context_id) |
| 347 | result.value = deserialize_result(result.value, self._driver) |
| 348 | return result |
| 349 | context = self._context(context_id) |
| 350 | raw = self._script.call_function( |
| 351 | function_declaration=function_declaration, |
| 352 | await_promise=True, |
| 353 | target={"context": context} if context else {}, |
| 354 | arguments=[serialize_argument(a) for a in args] if args else None, |
| 355 | ) |
| 356 | if isinstance(raw, dict) and raw.get("type") == "exception": |
| 357 | details = raw.get("exceptionDetails") |
| 358 | message = details.get("text", str(details)) if isinstance(details, dict) else str(details) |
| 359 | raise JavascriptException(message) |
| 360 | if isinstance(raw, dict) and raw.get("type") == "success": |
| 361 | raw = raw.get("result") |
| 362 | return deserialize_result(raw, self._driver) |
| 363 | |
| 364 | def add_console_handler(self, callback: Callable[[ConsoleMessage], Any]) -> int: |
| 365 | """Add a handler called with a ``ConsoleMessage`` for each console message. |