clipboard_documentation.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from nicegui import ui
  2. from . import doc
  3. @doc.demo('Read and write to the clipboard', '''
  4. The following demo shows how to use `ui.clipboard.read()`, `ui.clipboard.write()` and `ui.clipboard.read_image()` to interact with the clipboard.
  5. Because auto-index page can be accessed by multiple browser tabs simultaneously, reading the clipboard is not supported on this page.
  6. This is only possible within page-builder functions decorated with `ui.page`, as shown in this demo.
  7. Note that your browser may ask for permission to access the clipboard or may not support this feature at all.
  8. ''')
  9. def main_demo() -> None:
  10. # @ui.page('/')
  11. # async def index():
  12. with ui.column(): # HIDE
  13. ui.button('Write Text', on_click=lambda: ui.clipboard.write('Hi!'))
  14. async def read() -> None:
  15. ui.notify(await ui.clipboard.read())
  16. ui.button('Read Text', on_click=read)
  17. async def read_image() -> None:
  18. img = await ui.clipboard.read_image()
  19. if not img:
  20. ui.notify('You must copy an image to clipboard first.')
  21. else:
  22. image.set_source(img)
  23. ui.button('Read Image', on_click=read_image)
  24. image = ui.image().classes('w-72')
  25. @doc.demo('Client-side clipboard', '''
  26. In order to avoid the round-trip to the server, you can also use the client-side clipboard API directly.
  27. This might be supported by more browsers because the clipboard access is directly triggered by a user action.
  28. ''')
  29. def client_side_clipboard() -> None:
  30. ui.button('Write').on('click', js_handler='''
  31. () => navigator.clipboard.writeText("Ho!")
  32. ''')
  33. ui.button('Read').on('click', js_handler='''
  34. async () => emitEvent("clipboard", await navigator.clipboard.readText())
  35. ''')
  36. ui.on('clipboard', lambda e: ui.notify(e.args))