javascript.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from typing import Optional
  2. from .. import context
  3. from ..awaitable_response import AwaitableResponse
  4. from ..logging import log
  5. def run_javascript(code: str, *,
  6. respond: Optional[bool] = None, # DEPRECATED
  7. timeout: float = 1.0, check_interval: float = 0.01) -> AwaitableResponse:
  8. """Run JavaScript
  9. This function runs arbitrary JavaScript code on a page that is executed in the browser.
  10. The client must be connected before this function is called.
  11. To access a client-side object by ID, use the JavaScript function `getElement()`.
  12. If the function is awaited, the result of the JavaScript code is returned.
  13. Otherwise, the JavaScript code is executed without waiting for a response.
  14. :param code: JavaScript code to run
  15. :param timeout: timeout in seconds (default: `1.0`)
  16. :param check_interval: interval in seconds to check for a response (default: `0.01`)
  17. :return: AwaitableResponse that can be awaited to get the result of the JavaScript code
  18. """
  19. if respond is True:
  20. log.warning('The "respond" argument of run_javascript() has been removed. '
  21. 'Now the function always returns an AwaitableResponse that can be awaited. '
  22. 'Please remove the "respond=True" argument.')
  23. if respond is False:
  24. raise ValueError('The "respond" argument of run_javascript() has been removed. '
  25. 'Now the function always returns an AwaitableResponse that can be awaited. '
  26. 'Please remove the "respond=False" argument and call the function without awaiting.')
  27. client = context.get_client()
  28. if not client.has_socket_connection:
  29. raise RuntimeError('Cannot run JavaScript before client is connected; '
  30. 'try "await client.connected()" or "client.on_connect(...)".')
  31. return client.run_javascript(code, timeout=timeout, check_interval=check_interval)