JavaScript
javascript clipboard utility

copyToClipboard

Async utility function for copying text to clipboard with fallback support.

export async function copyToClipboard(text: string): Promise<boolean> {
  try {
    // Modern Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
      return true;
    }

    // Fallback for older browsers
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    textArea.style.top = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
      const successful = document.execCommand('copy');
      document.body.removeChild(textArea);
      return successful;
    } catch (err) {
      document.body.removeChild(textArea);
      return false;
    }
  } catch (err) {
    console.error('Failed to copy text:', err);
    return false;
  }
}

Usage

// In a React component
async function handleCopy() {
  const success = await copyToClipboard('Text to copy');
  if (success) {
    console.log('Copied to clipboard!');
  }
}

// With error handling
try {
  await copyToClipboard(codeSnippet);
  showToast('Copied to clipboard!');
} catch (error) {
  showToast('Failed to copy', 'error');
}