Skip to content

Function: copyToClipboard()

ts
function copyToClipboard(
  text: string,
  onSuccess?: () => void,
  onFailure?: (error: Error) => void,
): void;

Copies text to the system clipboard using multiple fallback strategies for maximum compatibility.

This function implements a progressive enhancement approach with three fallback methods:

  1. Modern Clipboard API (preferred) - Most secure, requires HTTPS/localhost
  2. Document.execCommand('copy') - Legacy browser support
  3. Manual prompt fallback - Ultimate compatibility when all else fails

Parameters

ParameterTypeDescription
textstringThe text content to copy to clipboard
onSuccess?() => voidOptional callback executed when copy operation succeeds
onFailure?(error: Error) => voidOptional callback executed when copy operation fails, receives error details

Returns

void

Example

typescript
// Basic usage
copyToClipboard("Hello World!");

// With callbacks
copyToClipboard(
  "Important data",
  () => console.log("Copied successfully!"),
  (error) => console.error("Copy failed:", error.message),
);

// In Vue component with user feedback
const handleCopy = (text: string) => {
  copyToClipboard(
    text,
    () => showNotification("Copied to clipboard!"),
    (error) => showNotification(`Copy failed: ${error.message}`),
  );
};

Remarks

  • Clipboard API requires secure context (HTTPS or localhost)
  • execCommand fallback works in older browsers but is deprecated
  • Manual prompt ensures functionality even in restricted environments
  • SSR-safe with proper browser environment detection