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:
- Modern Clipboard API (preferred) - Most secure, requires HTTPS/localhost
- Document.execCommand('copy') - Legacy browser support
- Manual prompt fallback - Ultimate compatibility when all else fails
Parameters
| Parameter | Type | Description |
|---|---|---|
text | string | The text content to copy to clipboard |
onSuccess? | () => void | Optional callback executed when copy operation succeeds |
onFailure? | (error: Error) => void | Optional 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