How do I copy to the clipboard in JavaScript?

To copy text to the clipboard in JavaScript, you can use the modern Clipboard API (recommended) or the legacy execCommand method. Here’s how to implement both approaches:

1. Modern Clipboard API (Async/Promise-based)

// Copy text to clipboard (modern browsers)
async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    console.log('Text copied to clipboard');
    return true;
  } catch (err) {
    console.error('Failed to copy:', err);
    return false;
  }
}

// Usage
copyToClipboard("Hello, World!");

Key Notes:

  • Requires HTTPS in most browsers (secure context).
  • Works in Chrome, Firefox, Edge, and Safari 13.4+.
  • Must be triggered by a user gesture (e.g., button click).

2. Legacy execCommand Method (Deprecated but widely supported)

function copyToClipboardLegacy(text) {
  // Create a temporary textarea element
  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.style.position = 'fixed'; // Hide off-screen
  document.body.appendChild(textarea);

  // Select and copy text
  textarea.select();
  try {
    const success = document.execCommand('copy');
    if (success) console.log('Text copied to clipboard');
    else console.error('Copy failed');
    return success;
  } catch (err) {
    console.error('Copy failed:', err);
    return false;
  } finally {
    document.body.removeChild(textarea); // Cleanup
  }
}

// Usage
copyToClipboardLegacy("Hello, World!");

Key Notes:

  • Supported in older browsers (IE 9+).
  • Requires DOM interaction (element creation/selection).
  • Deprecated but still used for backward compatibility.

Combined Approach (Fallback-Compatible)

function copyTextToClipboard(text) {
  // Use Clipboard API if available
  if (navigator.clipboard) {
    return navigator.clipboard.writeText(text).then(
      () => true,
      (err) => {
        console.error('Clipboard API failed, using fallback:', err);
        return copyToClipboardLegacy(text); // Use legacy method
      }
    );
  } else {
    // Fallback to legacy method
    return Promise.resolve(copyToClipboardLegacy(text));
  }
}

// Usage (async/await or .then())
copyTextToClipboard("Hello, World!")
  .then(success => {
    if (success) console.log('Copied!');
    else console.log('Failed to copy');
  });

Browser Compatibility

MethodBrowser Support
Clipboard APIChrome 66+, Firefox 63+, Edge 79+, Safari 13.4+
execCommandIE 9+, Edge 12+, Firefox 41+, Chrome 42+, Safari 10+

Best Practices

  1. User Interaction: Trigger clipboard actions via user events (e.g., button clicks).
  2. Error Handling: Always handle permission issues or unsupported browsers.
  3. Feedback: Show a toast/notification to indicate success/failure.

Example with a Button:

<button onclick="copyTextToClipboard('Copied!')">Copy Text</button>

Leave a Reply

Your email address will not be published. Required fields are marked *