diff --git a/web/src/lib/clipboard.ts b/web/src/lib/clipboard.ts index 30b402a..62e3a21 100644 --- a/web/src/lib/clipboard.ts +++ b/web/src/lib/clipboard.ts @@ -7,23 +7,17 @@ * 返回 Promise,表示是否成功复制 */ export async function copyToClipboard(text: string): Promise { - // 优先使用现代 Clipboard API try { if (typeof navigator !== 'undefined' && navigator.clipboard && typeof navigator.clipboard.writeText === 'function') { await navigator.clipboard.writeText(text); return true; } } catch (err) { - // 忽略并回退到老方法 - // console.warn('navigator.clipboard.writeText failed, falling back to execCommand', err); } - - // 回退到 textarea + execCommand 方案(在许多旧浏览器上可用) if (typeof document === 'undefined') return false; const textarea = document.createElement('textarea'); textarea.value = text; - // 防止页面滚动,把元素放到不可见但可选中的位置 textarea.setAttribute('readonly', ''); textarea.style.position = 'fixed'; textarea.style.left = '-9999px'; @@ -31,7 +25,6 @@ export async function copyToClipboard(text: string): Promise { textarea.style.opacity = '0'; document.body.appendChild(textarea); - // 保存当前 selection(以便恢复) const selection = document.getSelection(); let originalRange: Range | null = null; if (selection && selection.rangeCount > 0) { @@ -42,9 +35,7 @@ export async function copyToClipboard(text: string): Promise { textarea.setSelectionRange(0, textarea.value.length); try { - // 使用 any 绕开 TypeScript 中关于 execCommand 的弃用声明 - const successful = (document as any).execCommand('copy'); - // 清理并恢复 selection + const successful = document.execCommand('copy'); document.body.removeChild(textarea); if (selection) { selection.removeAllRanges(); @@ -52,7 +43,6 @@ export async function copyToClipboard(text: string): Promise { } return Boolean(successful); } catch (err) { - // 清理并恢复 selection document.body.removeChild(textarea); if (selection) { selection.removeAllRanges();