Explorar el Código

优化剪贴板复制功能,增加错误处理和降级方案

wuyi hace 1 mes
padre
commit
82c1092ea8
Se han modificado 1 ficheros con 42 adiciones y 7 borrados
  1. 42 7
      src/views/QrCodeManageView.vue

+ 42 - 7
src/views/QrCodeManageView.vue

@@ -312,15 +312,50 @@ const viewScanRecords = async (qrCode) => {
 }
 
 // 复制到剪贴板
-const copyToClipboard = (text) => {
-  navigator.clipboard.writeText(text).then(() => {
+const copyToClipboard = async (text) => {
+  try {
+    // 优先使用现代 Clipboard API
+    if (navigator.clipboard && window.isSecureContext) {
+      await navigator.clipboard.writeText(text)
+      toast.add({
+        severity: 'success',
+        summary: '成功',
+        detail: '已复制到剪贴板',
+        life: 2000
+      })
+    } else {
+      // 降级方案:使用传统的 document.execCommand
+      const textArea = document.createElement('textarea')
+      textArea.value = text
+      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) {
+        toast.add({
+          severity: 'success',
+          summary: '成功',
+          detail: '已复制到剪贴板',
+          life: 2000
+        })
+      } else {
+        throw new Error('复制失败')
+      }
+    }
+  } catch (error) {
     toast.add({
-      severity: 'success',
-      summary: '成功',
-      detail: '已复制到剪贴板',
-      life: 2000
+      severity: 'error',
+      summary: '错误',
+      detail: '复制失败,请手动复制',
+      life: 3000
     })
-  })
+  }
 }
 
 // 查看详情