refactor: 精简复制到剪贴板的实现,移除冗余注释和回退逻辑

This commit is contained in:
2025-09-12 15:51:59 +08:00
parent 5fab1806bc
commit f1a26f5e9c

View File

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