clipboard.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. function legacyCopyText(text: string): boolean {
  2. const textarea = document.createElement('textarea')
  3. const activeElement = document.activeElement instanceof HTMLElement ? document.activeElement : null
  4. textarea.value = text
  5. textarea.setAttribute('readonly', '')
  6. textarea.setAttribute('aria-hidden', 'true')
  7. textarea.style.cssText = 'position:fixed;left:-9999px;top:0;width:1px;height:1px;opacity:0'
  8. document.body.appendChild(textarea)
  9. textarea.focus({ preventScroll: true })
  10. textarea.select()
  11. textarea.setSelectionRange(0, text.length)
  12. let copied = false
  13. try {
  14. copied = document.execCommand('copy')
  15. } catch {
  16. copied = false
  17. } finally {
  18. textarea.remove()
  19. activeElement?.focus({ preventScroll: true })
  20. }
  21. return copied
  22. }
  23. /** Copy text in secure browsers and in embedded/HTTP browsers with a legacy fallback. */
  24. export async function copyTextToClipboard(text: string): Promise<boolean> {
  25. try {
  26. if (window.isSecureContext && navigator.clipboard?.writeText) {
  27. await navigator.clipboard.writeText(text)
  28. return true
  29. }
  30. } catch {
  31. // Permission-restricted embedded browsers can expose the API but reject it.
  32. }
  33. return legacyCopyText(text)
  34. }