{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 运行 JavaScript\n", "\n", "此函数在浏览器中执行页面上的任意 JavaScript 代码。在该函数被调用之前,客户端必须连接。要通过 ID 访问客户端对象,请使用 JavaScript 函数 `getElement()`。\n", "\n", "如果等待该函数,将返回 JavaScript 代码的结果。否则,将执行 JavaScript 代码,无需等待响应。\n", "\n", "参数:\n", "- `code`: 要运行的 JavaScript 代码\n", "- `timeout`: 超时时间(秒)(默认值:`1.0`)\n", "- `check_interval`: 检查响应的时间间隔(秒)(默认值:`0.01`)\n", "- 返回值:可等待的 `AwaitableResponse`,可以等待以获取 JavaScript 代码的结果" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from nicegui import ui\n", "\n", "def alert():\n", " ui.run_javascript('alert(\"Hello!\")')\n", "\n", "async def get_date():\n", " time = await ui.run_javascript('Date()')\n", " ui.notify(f'Browser time: {time}')\n", "\n", "def access_elements():\n", " ui.run_javascript(f'getElement({label.id}).innerText += \" Hello!\"')\n", "\n", "ui.button('fire and forget', on_click=alert)\n", "ui.button('receive result', on_click=get_date)\n", "ui.button('access elements', on_click=access_elements)\n", "label = ui.label()\n", "\n", "# ui.run()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 运行异步 JavaScript\n", "\n", "使用 `run_javascript`,您还可以在浏览器中运行异步代码。以下演示展示了如何获取用户的当前位置。" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from nicegui import ui\n", "\n", "async def show_location():\n", " response = await ui.run_javascript('''\n", " return await new Promise((resolve, reject) => {\n", " if (!navigator.geolocation) {\n", " reject(new Error('Geolocation is not supported by your browser'));\n", " } else {\n", " navigator.geolocation.getCurrentPosition(\n", " (position) => {\n", " resolve({\n", " latitude: position.coords.latitude,\n", " longitude: position.coords.longitude,\n", " });\n", " },\n", " () => {\n", " reject(new Error('Unable to retrieve your location'));\n", " }\n", " );\n", " }\n", " });\n", " ''', timeout=5.0)\n", " ui.notify(f'Your location is {response[\"latitude\"]}, {response[\"longitude\"]}')\n", "\n", "ui.button('Show location', on_click=show_location)\n", "\n", "# ui.run()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "py311", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.7" } }, "nbformat": 4, "nbformat_minor": 2 }