export async function copyText(text: string) { if (window.isSecureContext && navigator.clipboard?.writeText) { try { await navigator.clipboard.writeText(text) return } catch { // HTTP 部署或宿主 WebView 里经常不可用,继续走兼容方案。 } } fallbackCopyText(text) } function fallbackCopyText(text: string) { const textarea = document.createElement('textarea') const previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null textarea.value = text 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.select() textarea.setSelectionRange(0, textarea.value.length) const copied = document.execCommand('copy') document.body.removeChild(textarea) previousFocus?.focus() if (!copied) { throw new Error('复制失败') } }