Files
syops/frontend/src/utils/clipboard.ts
T
2026-05-25 14:58:09 +08:00

37 lines
1017 B
TypeScript

/**
* Copy plain text to the clipboard with fallbacks for restricted browsers
* (e.g. WeCom embedded WebView, HTTP deployments).
*/
export async function copyTextToClipboard(text: string): Promise<boolean> {
const value = String(text ?? '');
if (!value.trim()) return false;
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(value);
return true;
} catch {
// Fall through to legacy copy.
}
}
try {
const textarea = document.createElement('textarea');
textarea.value = value;
textarea.setAttribute('readonly', 'true');
textarea.style.position = 'fixed';
textarea.style.left = '-9999px';
textarea.style.top = '0';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.focus();
textarea.select();
textarea.setSelectionRange(0, value.length);
const ok = document.execCommand('copy');
document.body.removeChild(textarea);
return ok;
} catch {
return false;
}
}