clipboard.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2019-2021 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. /**
  5. * Read and write to the system clipboard.
  6. *
  7. * This package is also accessible with `window.__TAURI__.clipboard` when [`build.withGlobalTauri`](https://tauri.app/v1/api/config/#buildconfig.withglobaltauri) in `tauri.conf.json` is set to `true`.
  8. * @module
  9. */
  10. import { invokeTauriCommand } from './helpers/tauri'
  11. /**
  12. * Writes plain text to the clipboard.
  13. * @example
  14. * ```typescript
  15. * import { writeText, readText } from '@tauri-apps/api/clipboard';
  16. * await writeText('Tauri is awesome!');
  17. * assert(await readText(), 'Tauri is awesome!');
  18. * ```
  19. *
  20. * @returns A promise indicating the success or failure of the operation.
  21. */
  22. async function writeText(text: string): Promise<void> {
  23. return invokeTauriCommand({
  24. __tauriModule: 'Clipboard',
  25. message: {
  26. cmd: 'writeText',
  27. data: text
  28. }
  29. })
  30. }
  31. /**
  32. * Gets the clipboard content as plain text.
  33. * @example
  34. * ```typescript
  35. * import { readText } from '@tauri-apps/api/clipboard';
  36. * const clipboardText = await readText();
  37. * ```
  38. *
  39. * @returns A promise resolving to the clipboard content as plain text.
  40. */
  41. async function readText(): Promise<string | null> {
  42. return invokeTauriCommand({
  43. __tauriModule: 'Clipboard',
  44. message: {
  45. cmd: 'readText',
  46. // if data is not set, `serde` will ignore the custom deserializer
  47. // that is set when the API is not allowlisted
  48. data: null
  49. }
  50. })
  51. }
  52. export { writeText, readText }