FIELD NOTE 022TypeScriptReviewed July 2026

Copy Text to Clipboard

Cross-browser implementation to copy text to clipboard with promise-based API

Copy the complete example or adapt its typed interface to your project. Comments are kept inside the snippet so the intent travels with the code.

pattern.ts
/**
 * Copy text to clipboard
 * @param text Text to copy
 * @returns Promise resolving to true if successful, false otherwise
 */
async function copyToClipboard(text: string): Promise<boolean> {
  try {
    if (navigator.clipboard) {
      // Modern browsers
      await navigator.clipboard.writeText(text);
    } else {
      // Fallback for older browsers
      const textArea = document.createElement('textarea');
      textArea.value = text;
      textArea.style.position = 'fixed'; // Prevent scrolling
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();
      document.execCommand('copy');
      document.body.removeChild(textArea);
    }
    return true;
  } catch (error) {
    console.error('Failed to copy:', error);
    return false;
  }
}

// Usage Example
copyToClipboard('Hello World!').then(success => {
  if (success) alert('Text copied to clipboard!');
});

Essential for copy buttons, code snippet copy functionality, or any feature requiring clipboard access

Implementation note

Review the input assumptions and browser or runtime support before adopting a utility unchanged. Small helpers are easiest to maintain when their contract stays narrow.

How it works

The Clipboard API writes a string through a promise and exposes success or failure to the caller. It avoids temporary textareas and selection manipulation in modern secure browser contexts.

What to watch for

Clipboard access generally requires HTTPS, a focused document, and a user gesture. Permissions and embedded-frame policy can block it, and writing secrets or unexpected content can undermine user trust.

Production use

Use copy controls beside content the user can already see, provide clear confirmation, and retain a manual-selection fallback when copying is important. Never trigger clipboard writes during page load or unrelated clicks.

Before you ship

  • Confirm the input contract with tests that cover empty, invalid, boundary, and representative real-world values before sharing the helper across a codebase.
  • Keep the function focused on one responsibility and name any project-specific policy explicitly instead of hiding it inside a generic-looking utility.
  • Measure behavior in the browsers or runtime versions your product supports, especially when timing, storage, DOM state, locale, or network access is involved.
  • Document the return type, mutation behavior, failure mode, and performance characteristics beside the call site so future maintainers can evaluate changes safely.
  • Compare the example with current official platform documentation when it relies on a browser API, language feature, or runtime behavior that may change over time.
  • If the helper crosses a trust boundary, validate again on the server and avoid treating browser-side checks, TypeScript annotations, or formatted output as a security guarantee.
  • Add a small regression test whenever a real edge case is discovered; concrete examples preserve the reason behind a guard more reliably than a general comment.