Overview
ThecopyToClipboard function provides a modern way to copy content to the clipboard using the Clipboard API, with automatic fallback to legacy methods for broader browser support.
Import
Signature
Parameters
The content to copy to the clipboard. Can be a string, Blob, or a Promise that resolves to either.
Optional configuration object.
The MIME type of the content. Defaults to
"text/plain".Common values:"text/plain"(default)"text/html""image/png"
Callback function called when the copy operation succeeds.
Callback function called when the copy operation fails.
Callback function called after copy completes (whether via Clipboard API or fallback).
Return Value
A promise that resolves when the copy operation completes. Errors are caught internally and passed to
onError.Usage Examples
Basic Text Copy
With Success Callback
Copy HTML Content
Copy Image Blob
Copy with Async Content
React Integration Example
Types
CopyToClipboardOptions
AllowedClipboardItems
Behavior
- Primary Method: Uses the modern Clipboard API (
navigator.clipboard.write) - MIME Type Check: Validates that the specified MIME type is supported
- Fallback: For text content, automatically falls back to
document.execCommand('copy')if the Clipboard API fails - Error Handling: All errors are caught and logged, with optional
onErrorcallback
Browser Support
- Modern Browsers: Full support via Clipboard API
- Legacy Browsers: Automatic fallback for text content
- HTTPS Required: Clipboard API requires secure context (HTTPS or localhost)
Common Use Cases
- Copy code snippets from documentation
- Copy share links or URLs
- Copy formatted text or HTML
- Copy generated content (tokens, IDs, etc.)
- Copy images or other media
Notes
- The Clipboard API requires a secure context (HTTPS or localhost)
- Some MIME types may not be supported in all browsers
- The fallback method only works for string content
- For better UX, always provide user feedback via callbacks
- The
onCopiedcallback fires regardless of whether the primary or fallback method was used