The problem
Need to copy text to user's clipboard
The solution
async function copyToClipboard(text) {
try {
// Use modern Clipboard API
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return true;
} else {
// Fallback for older browsers
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
const success = document.execCommand('copy');
document.body.removeChild(textarea);
return success;
}
} catch (error) {
console.error('Copy failed:', error);
return false;
}
}Parameters
textstringText to copy
Put it to work
// Copy static text
const success = await copyToClipboard('Hello, World!');
if (success) {
alert('Copied to clipboard!');
}
// Copy dynamic content
const element = document.querySelector('#content');
copyToClipboard(element.textContent);
// Copy with feedback
async function copyWithFeedback(text, successMsg = 'Copied!') {
if (await copyToClipboard(text)) {
console.log(successMsg);
} else {
console.error('Copy failed');
}
}