ソースを参照

fix: clipboard block not working in firefox

Ahmad Kholid 2 年 前
コミット
995c61b12e

+ 11 - 3
src/workflowEngine/blocksHandler/handlerClipboard.js

@@ -1,4 +1,5 @@
 import browser from 'webextension-polyfill';
+import { copyTextToClipboard } from '../helper';
 
 function doCommand(command, value) {
   const textarea = document.createElement('textarea');
@@ -21,11 +22,12 @@ function doCommand(command, value) {
 }
 
 export default async function ({ data, id, label }) {
-  if (!this.engine?.isPopup && !this.engins?.isMV2)
+  const isFirefox = BROWSER_TYPE === 'firefox';
+  if (!isFirefox && !this.engine?.isPopup && !this.engins?.isMV2)
     throw new Error('Clipboard block is not supported in background execution');
 
   const permissions = ['clipboardRead'];
-  if (BROWSER_TYPE === 'firefox') {
+  if (isFirefox) {
     permissions.push('clipboardWrite');
   }
 
@@ -64,7 +66,13 @@ export default async function ({ data, id, label }) {
     }
 
     valueToReturn = text;
-    doCommand('copy', text);
+
+    if (isFirefox) {
+      console.log('hello');
+      await copyTextToClipboard(text);
+    } else {
+      doCommand('copy', text);
+    }
   }
 
   return {

+ 39 - 0
src/workflowEngine/helper.js

@@ -312,3 +312,42 @@ export async function checkCSPAndInject(
 
   return { isBlocked: false, value: null };
 }
+
+function fallbackCopyTextToClipboard(text) {
+  const textArea = document.createElement('textarea');
+  textArea.value = text;
+
+  // Avoid scrolling to bottom
+  textArea.style.top = '0';
+  textArea.style.left = '0';
+  textArea.style.position = 'fixed';
+
+  document.body.appendChild(textArea);
+  textArea.focus();
+  textArea.select();
+
+  try {
+    document.execCommand('copy');
+  } catch (err) {
+    console.error('Fallback: Oops, unable to copy', err);
+  }
+
+  document.body.removeChild(textArea);
+}
+export function copyTextToClipboard(text) {
+  return new Promise((resolve, reject) => {
+    if (!navigator.clipboard) {
+      fallbackCopyTextToClipboard(text);
+      resolve(true);
+      return;
+    }
+    navigator.clipboard
+      .writeText(text)
+      .then(() => {
+        resolve(true);
+      })
+      .catch((error) => {
+        reject(error);
+      });
+  });
+}