clipboard_documentation.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  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()` and `ui.clipboard.write()` 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', on_click=lambda: ui.clipboard.write('Hi!'))
  14. async def read() -> None:
  15. ui.notify(await ui.clipboard.read())
  16. ui.button('Read', on_click=read)
  17. @doc.demo('Client-side clipboard', '''
  18. In order to avoid the round-trip to the server, you can also use the client-side clipboard API directly.
  19. This might be supported by more browsers because the clipboard access is directly triggered by a user action.
  20. ''')
  21. def client_side_clipboard() -> None:
  22. ui.button('Write').on('click', js_handler='''
  23. () => navigator.clipboard.writeText("Ho!")
  24. ''')
  25. ui.button('Read').on('click', js_handler='''
  26. async () => emitEvent("clipboard", await navigator.clipboard.readText())
  27. ''')
  28. ui.on('clipboard', lambda e: ui.notify(e.args))