30 lines
940 B
TypeScript
30 lines
940 B
TypeScript
/** Copy text to clipboard with execCommand fallback for older browsers. */
|
|
export function copyToClipboard(text: string, onSuccess: () => void): void {
|
|
if (navigator.clipboard?.writeText) {
|
|
navigator.clipboard
|
|
.writeText(text)
|
|
.then(onSuccess)
|
|
.catch(() => {
|
|
// Fallback if clipboard permission denied
|
|
const ta = document.createElement('textarea');
|
|
ta.value = text;
|
|
ta.style.position = 'fixed';
|
|
ta.style.opacity = '0';
|
|
document.body.appendChild(ta);
|
|
ta.select();
|
|
document.execCommand('copy');
|
|
document.body.removeChild(ta);
|
|
onSuccess();
|
|
});
|
|
} else {
|
|
const ta = document.createElement('textarea');
|
|
ta.value = text;
|
|
ta.style.position = 'fixed';
|
|
ta.style.opacity = '0';
|
|
document.body.appendChild(ta);
|
|
ta.select();
|
|
document.execCommand('copy');
|
|
document.body.removeChild(ta);
|
|
onSuccess();
|
|
}
|
|
}
|