Browse Source

复制兼容不是https造成的clipboard api 缺失

xiongxing 4 months ago
parent
commit
c921952e84
1 changed files with 23 additions and 1 deletions
  1. 23 1
      src/views/Home/Index.vue

+ 23 - 1
src/views/Home/Index.vue

@@ -281,13 +281,35 @@ const handleGridDataStatistics = async () => {
   }
 }
 
+const fallbackCopyText = (text: string) => {
+  const textarea = document.createElement('textarea')
+  textarea.value = text
+  textarea.setAttribute('readonly', 'readonly')
+  textarea.style.position = 'fixed'
+  textarea.style.left = '-9999px'
+  textarea.style.top = '0'
+  document.body.appendChild(textarea)
+  textarea.select()
+  const ok = document.execCommand('copy')
+  document.body.removeChild(textarea)
+  return ok
+}
+
 const handleCopyStatistics = async () => {
   if (!statsText.value) {
     ElMessage.warning('暂无可复制内容')
     return
   }
+
   try {
-    await navigator.clipboard.writeText(statsText.value)
+    if (window.isSecureContext && navigator.clipboard?.writeText) {
+      await navigator.clipboard.writeText(statsText.value)
+    } else {
+      const copied = fallbackCopyText(statsText.value)
+      if (!copied) {
+        throw new Error('fallback copy failed')
+      }
+    }
     ElMessage.success('复制成功')
   } catch (error) {
     ElMessage.error('复制失败,请手动复制')