The modern way to copy text is with the navigator.clipboard.writeText() API. It returns a Promise.
Basic Usage
Call navigator.clipboard.writeText(text) inside a user-gesture event (click, etc.).
Fallback
For older browsers, use document.execCommand('copy') with a temporary textarea element.
Security
The Clipboard API requires the page to be served over HTTPS (or localhost) and requires a user gesture.
Example
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Copied!');
} catch (err) {
// Fallback for older browsers
const el = document.createElement('textarea');
el.value = text;
el.style.position = 'fixed';
el.style.opacity = '0';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
}
// Usage
document.getElementById('copy-btn').addEventListener('click', () => {
copyToClipboard('Hello, World!');
});