Clipboard API
You'll learn how to read from and write to the user's system clipboard programmatically using modern JavaScript.
What Is the Clipboard API?
The Clipboard API provides a secure, asynchronous way to interact with the system clipboard—the invisible storage area that holds copied text, images, or other data when you press Ctrl+C or Cmd+C. Instead of relying on older techniques like document.execCommand(), you can now use navigator.clipboard to read what the user has copied or write new content to it.
Basic Clipboard Operations
The API centers around navigator.clipboard, which offers methods that return promises:
// Writing text to the clipboard
navigator.clipboard.writeText('Hello, clipboard!')
.then(() => console.log('Text copied!'))
.catch(err => console.error('Failed to copy:', err));
// Reading text from the clipboard
navigator.clipboard.readText()
.then(text => console.log('Clipboard contains:', text))
.catch(err => console.error('Failed to read:', err));
Permissions Matter
Unlike some browser APIs, clipboard access requires user permission for reading (writing usually requires a user gesture like a button click). The browser may prompt the user before allowing your code to peek at clipboard contents:
// Check permission status
navigator.permissions.query({ name: 'clipboard-read' })
.then(result => {
console.log('Clipboard permission:', result.state); // 'granted', 'denied', or 'prompt'
});
Think of it like a locked drawer: you can slip notes in (write), but opening it to see what's inside (read) requires the owner's explicit permission.
Security and User Gestures
Browsers enforce that writeText() typically works only in response to user actions (clicks, keypresses) to prevent malicious sites from spamming the clipboard without consent.
Key Takeaway: Use navigator.clipboard.writeText() to copy text to the clipboard and readText() to retrieve it, always respecting that reading requires user permission and writing needs a user gesture.