clipboard.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { invokeTauriCommand } from './helpers/tauri.js';
  2. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  3. // SPDX-License-Identifier: Apache-2.0
  4. // SPDX-License-Identifier: MIT
  5. /**
  6. * Read and write to the system clipboard.
  7. *
  8. * 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`.
  9. *
  10. * The APIs must be added to [`tauri.allowlist.clipboard`](https://tauri.app/v1/api/config/#allowlistconfig.clipboard) in `tauri.conf.json`:
  11. * ```json
  12. * {
  13. * "tauri": {
  14. * "allowlist": {
  15. * "clipboard": {
  16. * "all": true, // enable all Clipboard APIs
  17. * "writeText": true,
  18. * "readText": true
  19. * }
  20. * }
  21. * }
  22. * }
  23. * ```
  24. * It is recommended to allowlist only the APIs you use for optimal bundle size and security.
  25. *
  26. * @module
  27. */
  28. /**
  29. * Writes plain text to the clipboard.
  30. * @example
  31. * ```typescript
  32. * import { writeText, readText } from '@tauri-apps/api/clipboard';
  33. * await writeText('Tauri is awesome!');
  34. * assert(await readText(), 'Tauri is awesome!');
  35. * ```
  36. *
  37. * @returns A promise indicating the success or failure of the operation.
  38. *
  39. * @since 1.0.0.
  40. */
  41. async function writeText(text) {
  42. return invokeTauriCommand({
  43. __tauriModule: 'Clipboard',
  44. message: {
  45. cmd: 'writeText',
  46. data: text
  47. }
  48. });
  49. }
  50. /**
  51. * Gets the clipboard content as plain text.
  52. * @example
  53. * ```typescript
  54. * import { readText } from '@tauri-apps/api/clipboard';
  55. * const clipboardText = await readText();
  56. * ```
  57. * @since 1.0.0.
  58. */
  59. async function readText() {
  60. return invokeTauriCommand({
  61. __tauriModule: 'Clipboard',
  62. message: {
  63. cmd: 'readText',
  64. // if data is not set, `serde` will ignore the custom deserializer
  65. // that is set when the API is not allowlisted
  66. data: null
  67. }
  68. });
  69. }
  70. export { readText, writeText };