Browse Source

fix: http cannot be copied

The use of navigator.clipboard requires a secure origin. So if your dev environment is being served over HTTP, then the clipboard method won't be available.
chenjingjie 2 years ago
parent
commit
8f22f8187c
1 changed files with 19 additions and 2 deletions
  1. 19 2
      client/src/components/advancedSearch/CopyButton.tsx

+ 19 - 2
client/src/components/advancedSearch/CopyButton.tsx

@@ -13,12 +13,29 @@ const CopyButton: FC<CopyButtonProps> = props => {
   const { t: commonTrans } = useTranslation();
   const { t: commonTrans } = useTranslation();
   const copyTrans = commonTrans('copy');
   const copyTrans = commonTrans('copy');
   const [tooltipTitle, setTooltipTitle] = useState('Copy');
   const [tooltipTitle, setTooltipTitle] = useState('Copy');
-
+  
+  const unsecuredCopyToClipboard = (v: string) => {
+    const textArea = document.createElement("textarea");
+    textArea.style.position = 'fixed';
+    textArea.style.opacity = '0';
+    textArea.style.zIndex = '-1000';
+    textArea.value = v;
+    document.body.appendChild(textArea);
+    textArea.focus();
+    textArea.select();
+    try {
+      document.execCommand('copy');
+    } catch (err) {
+      console.error('Unable to copy to clipboard', err);
+    }
+    document.body.removeChild(textArea);
+  }
+  
   const handleClick = (event: React.MouseEvent<HTMLElement>, v: string) => {
   const handleClick = (event: React.MouseEvent<HTMLElement>, v: string) => {
     event.stopPropagation();
     event.stopPropagation();
 
 
     setTooltipTitle(copyTrans.copied);
     setTooltipTitle(copyTrans.copied);
-    navigator.clipboard.writeText(v);
+    (navigator.clipboard?.writeText ?? unsecuredCopyToClipboard)?.(v);
     setTimeout(() => {
     setTimeout(() => {
       setTooltipTitle(copyTrans.copy);
       setTooltipTitle(copyTrans.copy);
     }, 1000);
     }, 1000);