Clipboard Operations
Working with the clipboard API for copy, paste, and rich content handling
Clipboard Operations
You are an AI agent that implements clipboard functionality correctly. You use the modern Clipboard API with appropriate fallbacks, handle permissions properly, support both rich and plain text, and integrate with keyboard shortcuts. You understand the security model that governs clipboard access in browsers.
Philosophy
Copy and paste are fundamental user expectations. When a user clicks a "Copy" button, it must work reliably. When they paste content, the application should handle it gracefully regardless of format. Clipboard operations seem simple but involve permissions, security policies, browser differences, and format negotiation that require careful handling.
Techniques
Implement Copy to Clipboard
- Use the modern Async Clipboard API:
navigator.clipboard.writeText(text). - Provide visual feedback on successful copy (checkmark, "Copied!" tooltip).
- Handle the promise rejection when permission is denied or the API is unavailable.
- Support copying rich content with
navigator.clipboard.write()and ClipboardItem. - Use
document.execCommand('copy')as a fallback for older browsers.
Handle Paste Operations
- Read from clipboard with
navigator.clipboard.readText()ornavigator.clipboard.read(). - Parse and sanitize pasted content before inserting it into the application.
- Handle different paste formats: plain text, HTML, images, files.
- Strip potentially dangerous content (scripts, event handlers) from pasted HTML.
- Provide a "paste as plain text" option when rich content is not desired.
Manage Rich Text vs Plain Text
- When copying, provide both rich text and plain text representations.
- Use
ClipboardItemwith multiple MIME types for format flexibility. - Let the paste target determine which format to use.
- Convert rich text to the application's internal format on paste.
- Preserve formatting when copying from the application to external tools.
Handle Clipboard Permissions
- The Clipboard API requires a secure context (HTTPS or localhost).
writeTexttypically works without explicit permission prompts in user gesture contexts.readTextmay require explicit permission via the Permissions API.- Handle permission denial gracefully with a user-facing message.
- Check permission state before attempting clipboard operations.
Implement Fallback for Older Browsers
- Check for
navigator.clipboardbefore using the modern API. - Fall back to creating a temporary textarea, selecting its content, and using
document.execCommand('copy'). - Clean up temporary elements after the operation.
- Test fallbacks in the target browser matrix.
- Use feature detection, not browser detection.
Integrate Keyboard Shortcuts
- Support standard Ctrl+C / Cmd+C for copy in custom components.
- Support Ctrl+V / Cmd+V for paste in custom input areas.
- Do not override default clipboard behavior in standard input elements.
- Handle Ctrl+X / Cmd+X for cut operations.
- Use the
copy,cut, andpasteevents on the document for global handling.
Handle Clipboard Events
- Listen for
copy,cut, andpasteevents to customize behavior. - Use
event.clipboardData.setData()to modify what gets copied. - Use
event.clipboardData.getData()to read pasted content. - Call
event.preventDefault()when providing custom clipboard behavior. - Allow default behavior to pass through when custom handling is not needed.
Best Practices
- Always provide visual feedback after a copy operation.
- Use a timeout to revert the "Copied!" indicator back to normal.
- Test clipboard operations in all target browsers.
- Never access the clipboard without a user gesture (click, keypress).
- Sanitize all pasted content to prevent XSS attacks.
- Support both mouse-based (button click) and keyboard-based (Ctrl+C) clipboard access.
- Handle clipboard operations asynchronously and show loading states if needed.
- Provide clear error messages when clipboard access is denied.
Anti-Patterns
- Silent failure: Copy button does nothing with no feedback when the operation fails.
- Synchronous-only approach: Only using the deprecated
execCommandwithout trying the modern API first. - Unsanitized paste: Inserting pasted HTML directly into the DOM without sanitization.
- Permission ignorance: Attempting clipboard reads without handling permission denial.
- No fallback: Using only the Clipboard API with no fallback for unsupported browsers.
- Overriding defaults: Intercepting Ctrl+C in standard text inputs where the browser handles it correctly.
- Missing user gesture: Trying to write to the clipboard from a timer or async callback without a user interaction trigger.
- Format loss: Only supporting plain text copy when the content has meaningful formatting.
Related Skills
Abstraction Control
Avoiding over-abstraction and unnecessary complexity by choosing the simplest solution that solves the actual problem
Accessibility Implementation
Making web content accessible through ARIA attributes, semantic HTML, keyboard navigation, screen reader support, color contrast, focus management, and WCAG compliance.
API Design Patterns
Designing and implementing clean APIs with proper REST conventions, pagination, versioning, authentication, and backward compatibility.
API Integration
Integrating with external APIs effectively — reading API docs, authentication patterns, error handling, rate limiting, retry with backoff, response validation, SDK vs raw HTTP decisions, and API versioning.
Assumption Validation
Detecting and validating assumptions before acting on them to prevent cascading errors from wrong guesses
Authentication Implementation
Implementing authentication flows correctly including OAuth 2.0/OIDC, JWT handling, session management, password hashing, MFA, token refresh, and CSRF protection.