MCPcopy Create free account
hub / github.com/SeleniumHQ/selenium / Script

Class Script

py/selenium/webdriver/remote/script.py:283–466  ·  view source on GitHub ↗

Pinned scripts, script execution and script event handlers. Obtain it with ``driver.script``; do not construct it directly.

Source from the content-addressed store, hash-verified

281
282
283class Script:
284 """Pinned scripts, script execution and script event handlers.
285
286 Obtain it with ``driver.script``; do not construct it directly.
287 """
288
289 def __init__(self, script: Any, driver: WebDriver | None = None) -> None:
290 self._script = script
291 self._driver = driver
292
293 def _context(self, context_id: str | None) -> str | None:
294 if context_id is None and self._driver is not None:
295 return self._driver.current_window_handle
296 return context_id
297
298 def pin(self, function_declaration: str) -> PinnedScript:
299 """Pin a script so it runs in every new document and can be reused by ``execute()``.
300
301 Args:
302 function_declaration: The JavaScript function declaration to pin,
303 e.g. ``"() => { window.helper = () => 42 }"``.
304
305 Returns:
306 A ``PinnedScript`` to pass to ``execute()`` and ``unpin()``.
307 """
308 return self._script.pin(function_declaration)
309
310 def unpin(self, script_id: PinnedScript | str) -> None:
311 """Remove a pinned script.
312
313 Args:
314 script_id: The ``PinnedScript`` returned by ``pin()``.
315 """
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.

Calls

no outgoing calls