]> source.dussan.org Git - gitea.git/commitdiff
Re-allow clipboard copy on non-https sites (#17118)
authorNetduma Luke M <luke.meppem@netduma.com>
Tue, 19 Oct 2021 10:22:16 +0000 (11:22 +0100)
committerGitHub <noreply@github.com>
Tue, 19 Oct 2021 10:22:16 +0000 (18:22 +0800)
* Re-allow clipboard copy on non-https sites
* fallback clipboard functions

web_src/js/features/clipboard.js

index 4781f8d6ff4a4c4fca9cf0bac41e1c4e75018964..2c7ad013bd90c50fad48a48ebbfc3f7d5f8d79fb 100644 (file)
@@ -16,6 +16,33 @@ function onError(btn) {
   btn.dataset.content = btn.dataset.original;
 }
 
+/**
+ * Fallback to use if navigator.clipboard doesn't exist.
+ * Achieved via creating a temporary textarea element, selecting the text, and using document.execCommand.
+ */
+function fallbackCopyToClipboard(text) {
+  if (!document.execCommand) return false;
+
+  const tempTextArea = document.createElement('textarea');
+  tempTextArea.value = text;
+
+  // avoid scrolling
+  tempTextArea.style.top = 0;
+  tempTextArea.style.left = 0;
+  tempTextArea.style.position = 'fixed';
+
+  document.body.appendChild(tempTextArea);
+
+  tempTextArea.select();
+
+  // if unsecure (not https), there is no navigator.clipboard, but we can still use document.execCommand to copy to clipboard
+  const success = document.execCommand('copy');
+
+  document.body.removeChild(tempTextArea);
+
+  return success;
+}
+
 export default function initGlobalCopyToClipboardListener() {
   document.addEventListener('click', async (e) => {
     let target = e.target;
@@ -33,7 +60,11 @@ export default function initGlobalCopyToClipboardListener() {
           await navigator.clipboard.writeText(text);
           onSuccess(target);
         } catch {
-          onError(target);
+          if (fallbackCopyToClipboard(text)) {
+            onSuccess(target);
+          } else {
+            onError(target);
+          }
         }
         break;
       }