clipboard.ts 972 B

1234567891011121314151617181920212223242526272829303132333435
  1. export async function writeTextToClipboard(text: string): Promise<void> {
  2. if (navigator.clipboard && navigator.clipboard.writeText)
  3. return navigator.clipboard.writeText(text)
  4. return fallbackCopyTextToClipboard(text)
  5. }
  6. async function fallbackCopyTextToClipboard(text: string): Promise<void> {
  7. const textArea = document.createElement('textarea')
  8. textArea.value = text
  9. textArea.style.position = 'fixed' // Avoid scrolling to bottom
  10. document.body.appendChild(textArea)
  11. textArea.focus()
  12. textArea.select()
  13. try {
  14. const successful = document.execCommand('copy')
  15. if (successful)
  16. return Promise.resolve()
  17. return Promise.reject(new Error('document.execCommand failed'))
  18. }
  19. catch (err) {
  20. return Promise.reject(convertAnyToError(err))
  21. }
  22. finally {
  23. document.body.removeChild(textArea)
  24. }
  25. }
  26. function convertAnyToError(err: any): Error {
  27. if (err instanceof Error)
  28. return err
  29. return new Error(`Caught: ${String(err)}`)
  30. }