What is the Clipboard API?
The Clipboard API reads from and writes to the system clipboard asynchronously, replacing the old document.execCommand.
writeText / readText — copy and paste plain text via promises.
Permissions — reading usually needs permission; actions must follow a user gesture.
Secure context — requires HTTPS.
Always handle rejection — clipboard access can be denied by the user or browser.
// Copy to clipboard
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Copied!');
} catch (err) {
console.error('Copy failed:', err);
}
}
// Read from clipboard
async function pasteText() {
const text = await navigator.clipboard.readText();
console.log('Pasted:', text);
}
// Copy button
document.getElementById('copy-btn').addEventListener('click', () => {
copyText(document.getElementById('code').textContent);
});writeText copies text to clipboard asynchronously. readText reads from clipboard (requires permission). Both return Promises.
Requires HTTPS and user interaction (click handler). The copy button pattern is the most common use case.
navigator.clipboard.writeText/readText are the modern async APIs. Require HTTPS and user gesture.
The old document.execCommand('copy') is deprecated. Show the copy button pattern — most practical use case.