Copy text to the clipboard with a Promise-based API and fallback for older browsers.
export function copyToClipboard(text: string): Promise<void> {
if (navigator.clipboard?.writeText) {
return navigator.clipboard.writeText(text);
}
return new Promise((resolve, reject) => {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand('copy');
resolve();
} catch (e) {
reject(e);
} finally {
document.body.removeChild(textarea);
}
});
}Use in the browser. Returns a Promise that resolves when the text is copied. Uses navigator.clipboard when available, with execCommand fallback.
Call from a click handler. Handle errors for denied clipboard permission.
copyToClipboard('Hello').then(() => console.log('Copied')).catch(console.error);