Back to Snippets
CODE
Copy Text to Clipboard
Description
Cross-browser implementation to copy text to clipboard with promise-based API
Code
/**
* Copy text to clipboard
* @param text Text to copy
* @returns Promise resolving to true if successful, false otherwise
*/
async function copyToClipboard(text: string): Promise<boolean> {
try {
if (navigator.clipboard) {
// Modern browsers
await navigator.clipboard.writeText(text);
} else {
// Fallback for older browsers
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.position = 'fixed'; // Prevent scrolling
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
}
return true;
} catch (error) {
console.error('Failed to copy:', error);
return false;
}
}
// Usage Example
copyToClipboard('Hello World!').then(success => {
if (success) alert('Text copied to clipboard!');
});Usage
Essential for copy buttons, code snippet copy functionality, or any feature requiring clipboard access