yxh
10 天以前 bd3f4b0a9b9207b647de0f0d8c52600a2742fd56
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * 复制文本的兼容实现。
 *
 * 现场是 Chrome 85 且通过 http://内网IP 访问:
 *   · Chrome 85 的 navigator.clipboard 存在,但**非安全上下文(非 https/localhost)下不可用**;
 *   · 老版本浏览器可能根本没有 navigator.clipboard。
 * 直接 `navigator.clipboard.writeText()` 会抛 TypeError,复制按钮就"没反应"。
 *
 * 这里优先用 Clipboard API,失败/不可用时回退到 `document.execCommand('copy')`。
 */
export async function copyText(text: string): Promise<boolean> {
  if (!text) return false
 
  // ① 安全上下文 + 支持 Clipboard API 时才用它
  if (typeof navigator !== 'undefined' && navigator.clipboard && window.isSecureContext) {
    try {
      await navigator.clipboard.writeText(text)
      return true
    } catch {
      // 继续尝试兼容方案
    }
  }
 
  // ② 兼容方案:临时 textarea + execCommand(Chrome 85 / http 下可用)
  try {
    const textarea = document.createElement('textarea')
    textarea.value = text
    textarea.setAttribute('readonly', '')
    textarea.style.position = 'fixed'
    textarea.style.top = '-1000px'
    textarea.style.left = '-1000px'
    textarea.style.opacity = '0'
    document.body.appendChild(textarea)
    textarea.select()
    textarea.setSelectionRange(0, text.length)
    const ok = document.execCommand('copy')
    document.body.removeChild(textarea)
    return ok
  } catch {
    return false
  }
}