run_javascript_documentation.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from nicegui import ui
  2. from ...model import UiElementDocumentation
  3. class RunJavascriptDocumentation(UiElementDocumentation, element=ui.run_javascript):
  4. def main_demo(self) -> 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. def more(self) -> None:
  17. @self.demo('Run async JavaScript', '''
  18. Using `run_javascript` you can also run asynchronous code in the browser.
  19. The following demo shows how to get the current location of the user.
  20. ''')
  21. def run_async_javascript():
  22. async def show_location():
  23. response = await ui.run_javascript('''
  24. return await new Promise((resolve, reject) => {
  25. if (!navigator.geolocation) {
  26. reject(new Error('Geolocation is not supported by your browser'));
  27. } else {
  28. navigator.geolocation.getCurrentPosition(
  29. (position) => {
  30. resolve({
  31. latitude: position.coords.latitude,
  32. longitude: position.coords.longitude,
  33. });
  34. },
  35. () => {
  36. reject(new Error('Unable to retrieve your location'));
  37. }
  38. );
  39. }
  40. });
  41. ''', timeout=5.0)
  42. ui.notify(f'Your location is {response["latitude"]}, {response["longitude"]}')
  43. ui.button('Show location', on_click=show_location)