浏览代码

#242 improve documentation for run_javascript

Falko Schindler 2 年之前
父节点
当前提交
53fc14f8aa
共有 2 个文件被更改,包括 20 次插入6 次删除
  1. 14 0
      nicegui/functions/javascript.py
  2. 6 6
      website/reference.py

+ 14 - 0
nicegui/functions/javascript.py

@@ -5,6 +5,20 @@ from .. import globals
 
 async def run_javascript(code: str, *,
                          respond: bool = True, timeout: float = 1.0, check_interval: float = 0.01) -> Optional[str]:
+    """Run JavaScript
+
+    This function runs arbitrary JavaScript code on a page that is executed in the browser.
+    The asynchronous function will return after the command(s) are executed.
+    The client must be connected before this function is called.
+    To access a client-side object by ID, use the JavaScript function `getElement()`.
+
+    :param code: JavaScript code to run
+    :param respond: whether to wait for a response (default: `True`)
+    :param timeout: timeout in seconds (default: `1.0`)
+    :param check_interval: interval in seconds to check for a response (default: `0.01`)
+
+    :return: response from the browser, or `None` if `respond` is `False`
+    """
     client = globals.get_client()
     if not client.has_socket_connection:
         raise RuntimeError(

+ 6 - 6
website/reference.py

@@ -747,12 +747,7 @@ It also enables you to identify sessions using a [session middleware](https://ww
 
         ui.link('Visit session demo', session_demo)
 
-    @example('''#### JavaScript
-
-With `ui.run_javascript()` you can run arbitrary JavaScript code on a page that is executed in the browser.
-The asynchronous function will return after the command(s) are executed.
-You can also set `respond=False` to send a command without waiting for a response.
-''', menu)
+    @example(ui.run_javascript, menu)
     def javascript_example():
         async def alert():
             await ui.run_javascript('alert("Hello!")', respond=False)
@@ -761,8 +756,13 @@ You can also set `respond=False` to send a command without waiting for a respons
             time = await ui.run_javascript('Date()')
             ui.notify(f'Browser time: {time}')
 
+        async def access_elements():
+            await ui.run_javascript(f'getElement({label.id}).innerText += " Hello!"')
+
         ui.button('fire and forget', on_click=alert)
         ui.button('receive result', on_click=get_date)
+        ui.button('access elements', on_click=access_elements)
+        label = ui.label()
 
     h3('Routes')