/**
|
* 复制文本的兼容实现。
|
*
|
* 现场是 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
|
}
|
}
|