测试环境复制剪贴板内容失败

78 阅读1分钟

image.png

当我们需要复制到剪贴板一些数据的时候,本地开发是好的, 但是测试环境会出现复制失败的问题

在测试环境中复制失败,最常见的原因是:

测试的环境是http协议的,

http://192.168.10.666:6666/test

解决方法:

安全上下文限制 : navigator.clipboard API **必须在安全上下文(HTTPS)**中运行,

如果测试环境使用 HTTP 协议,此 API 会失败

用户交互要求 :剪贴板 API 要求在 用户主动交互事件链中 调用,某些测试环境可能不满足

浏览器兼容性 :不同浏览器对 navigator.clipboard API 的支持程度不同

解决方案:添加降级复制方案


const handleCopyData = async (data) => {
    try {
        // 优先尝试使用现代的 Clipboard API
        if (navigator.clipboard && window.isSecureContext) {
            await navigator.clipboard.writeText(data)
        } else {
            // 降级方案:使用传统的 execCommand 方法
            const textArea = document.createElement('textarea')
            textArea.value = data
            // 将文本域定位到视野外
            textArea.style.position = 'fixed'
            textArea.style.left = '-999999px'
            textArea.style.top = '-999999px'
            document.body.appendChild(textArea)
            textArea.focus()
            textArea.select()
            // 执行复制命令
            const successful = document.execCommand('copy')
            document.body.removeChild(textArea)

            if (!successful) {
                throw new Error('execCommand failed')
            }
        }

        ElMessage({ type: 'success', message: '复制成功' })
    } catch (err) {
        console.error('复制失败:', err)
        ElMessage({ type: 'error', message: '复制失败,请重试' })
    }
}