Modern Clipboard API
// Basic copy
async function copyText(text) {
await navigator.clipboard.writeText(text);
console.log('Copied!');
}
// With error handling
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Copied successfully');
} catch (err) {
console.error('Copy failed:', err);
}
}
💡 Note:
navigator.clipboard is Promise-based and requires async/await or .then(). It only works on HTTPS pages (or localhost for development).Copy Button Pattern
<!-- HTML -->
<div class="copy-wrap">
<code id="code-block">npm install your-package</code>
<button onclick="copyCode()" id="copy-btn">Copy</button>
</div>
// JS
async function copyCode() {
const text = document.getElementById('code-block').innerText;
try {
await navigator.clipboard.writeText(text);
showCopied();
} catch (err) {
fallbackCopy(text);
}
}
User Feedback After Copying
function showCopied() {
const btn = document.getElementById('copy-btn');
const original = btn.textContent;
btn.textContent = '✓ Copied!';
btn.style.color = '#4ade80';
setTimeout(() => {
btn.textContent = original;
btn.style.color = '';
}, 2000);
}
Fallback for Older Browsers
function fallbackCopy(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
}
Complete function with automatic fallback:
async function copyToClipboard(text) {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
} else {
// Fallback
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.cssText = 'position:fixed;opacity:0;pointer-events:none;';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
}
}
Permissions & HTTPS
- The Clipboard API requires HTTPS (or
localhost) - Writing to clipboard (
writeText) generally doesn't require user permission - Reading from clipboard (
readText) requires explicit user permission via the Permissions API - The fallback
execCommandworks on HTTP but is deprecated — use it only as a fallback