run_javascript_documentation.py 1.7 KB

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