clipboard.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /**
  2. * Handles copying text to the clipboard with a fallback for insecure contexts.
  3. * In non-HTTPS/non-localhost environments, navigator.clipboard is not available.
  4. */
  5. export const copyToClipboard = async (text: string): Promise<boolean> => {
  6. // 1. Try modern Clipboard API first (requires secure context)
  7. if (navigator.clipboard && window.isSecureContext) {
  8. try {
  9. await navigator.clipboard.writeText(text);
  10. return true;
  11. } catch (err) {
  12. console.error('Clipboard API failed:', err);
  13. // Fall through to fallback
  14. }
  15. }
  16. // 2. Fallback: document.execCommand('copy')
  17. try {
  18. const textArea = document.createElement('textarea');
  19. textArea.value = text;
  20. // Ensure the textarea is not visible but stays in the DOM
  21. textArea.style.position = 'fixed';
  22. textArea.style.left = '-9999px';
  23. textArea.style.top = '0';
  24. document.body.appendChild(textArea);
  25. textArea.focus();
  26. textArea.select();
  27. const successful = document.execCommand('copy');
  28. document.body.removeChild(textArea);
  29. return successful;
  30. } catch (err) {
  31. console.error('Fallback copy failed:', err);
  32. return false;
  33. }
  34. };