1
0

run_javascript_documentation.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from nicegui import ui
  2. from . import doc
  3. @doc.demo(ui.run_javascript)
  4. def main_demo() -> None:
  5. # @ui.page('/')
  6. def page():
  7. def alert():
  8. ui.run_javascript('alert("Hello!")')
  9. async def get_date():
  10. time = await ui.run_javascript('Date()')
  11. ui.notify(f'Browser time: {time}')
  12. def access_elements():
  13. ui.run_javascript(f'getElement({label.id}).innerText += " Hello!"')
  14. ui.button('fire and forget', on_click=alert)
  15. ui.button('receive result', on_click=get_date)
  16. ui.button('access elements', on_click=access_elements)
  17. label = ui.label()
  18. page() # HIDE
  19. @doc.demo('Run async JavaScript', '''
  20. Using `run_javascript` you can also run asynchronous code in the browser.
  21. The following demo shows how to get the current location of the user.
  22. ''')
  23. def run_async_javascript():
  24. # @ui.page('/')
  25. def page():
  26. async def show_location():
  27. response = await ui.run_javascript('''
  28. return await new Promise((resolve, reject) => {
  29. if (!navigator.geolocation) {
  30. reject(new Error('Geolocation is not supported by your browser'));
  31. } else {
  32. navigator.geolocation.getCurrentPosition(
  33. (position) => {
  34. resolve({
  35. latitude: position.coords.latitude,
  36. longitude: position.coords.longitude,
  37. });
  38. },
  39. () => {
  40. reject(new Error('Unable to retrieve your location'));
  41. }
  42. );
  43. }
  44. });
  45. ''', timeout=5.0)
  46. ui.notify(f'Your location is {response["latitude"]}, {response["longitude"]}')
  47. ui.button('Show location', on_click=show_location)
  48. page() # HIDE