What is the Clipboard API and how to use it
· Category: JavaScript & Web
Short answer
The Clipboard API provides asynchronous access to the system clipboard via navigator.clipboard.writeText() and readText(), secured behind user permissions and requiring a secure context (HTTPS or localhost).
Details
Copying text is straightforward:
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
} catch (err) {
console.error('Failed to copy:', err);
}
}
Reading from the clipboard requires explicit user permission and is typically gated behind a user gesture. Wrap clipboard calls in error handling with try/catch because browsers may deny access based on permissions or context. If you build a rich text editor, the Clipboard API pairs with JavaScript closures to maintain editor state across asynchronous paste events. For older browsers, keep a hidden <textarea> fallback that the user can manually select and copy.
Tips
- Always provide a visible button for clipboard actions; do not trigger them automatically without user intent.
- Sanitize pasted content before inserting it into the DOM to prevent XSS.
- Use
ClipboardItemand blob types when copying images or rich content, not just plain text.