Bläddra i källkod

fix: can't connect to active tab in firefox (#559)

Ahmad Kholid 2 år sedan
förälder
incheckning
77f9e0e771

+ 1 - 0
.eslintrc.js

@@ -34,6 +34,7 @@ module.exports = {
   rules: {
     camelcase: 'off',
     'no-await-in-loop': 'off',
+    'import/no-import-module-exports': 'off',
     'no-console': ['warn', { allow: ['warn', 'error'] }],
     'no-underscore-dangle': 'off',
     'func-names': 'off',

+ 2 - 2
src/background/workflowEngine/blocksHandler/handlerSwitchTo.js

@@ -1,4 +1,4 @@
-import { objectHasKey } from '@/utils/helper';
+import { objectHasKey, sleep } from '@/utils/helper';
 import { getBlockConnection, getFrames } from '../helper';
 
 async function switchTo(block) {
@@ -34,7 +34,7 @@ async function switchTo(block) {
     if (objectHasKey(frames, url)) {
       this.activeTab.frameId = frames[url];
 
-      await new Promise((resolve) => setTimeout(resolve, 1000));
+      await sleep(1000);
 
       return {
         data: this.activeTab.frameId,

+ 3 - 2
src/background/workflowEngine/engine.js

@@ -174,18 +174,19 @@ class WorkflowEngine {
   }
 
   addLogHistory(detail) {
-    if (detail.name === 'blocks-group') return;
+    if (['blocks-group', 'delay'].includes(detail.name)) return;
 
     const isLimit = this.history.length >= 1001;
     const notErrorLog = detail.type !== 'error';
 
-    if (!this.saveLog && isLimit && notErrorLog) return;
+    if ((isLimit || !this.saveLog) && notErrorLog) return;
 
     this.logHistoryId += 1;
     detail.id = this.logHistoryId;
 
     if (
       detail.replacedValue ||
+      detail.name === 'javascript-code' ||
       (tasks[detail.name]?.refDataKeys && this.saveLog)
     ) {
       const { activeTabUrl, variables, loopData } = JSON.parse(

+ 1 - 0
src/background/workflowEngine/helper.js

@@ -93,6 +93,7 @@ export function convertData(data, type) {
 
   switch (type) {
     case 'integer':
+      /* eslint-disable-next-line */
       result = typeof data !== 'number' ? +data?.replace(/\D+/g, '') : data;
       break;
     case 'boolean':

+ 47 - 0
src/background/workflowEngine/injectContentScript.js

@@ -0,0 +1,47 @@
+import browser from 'webextension-polyfill';
+
+async function contentScriptExist(tabId, frameId = 0) {
+  try {
+    await browser.tabs.sendMessage(
+      tabId,
+      { type: 'content-script-exists' },
+      { frameId }
+    );
+
+    return true;
+  } catch (error) {
+    return false;
+  }
+}
+
+export default function (tabId, frameId = 0) {
+  return new Promise((resolve) => {
+    const currentFrameId = typeof frameId !== 'number' ? 0 : frameId;
+    const tryCount = 0;
+
+    (async function tryExecute() {
+      try {
+        if (tryCount > 3) {
+          resolve(false);
+          return;
+        }
+
+        await browser.tabs.executeScript(tabId, {
+          allFrames: true,
+          runAt: 'document_end',
+          file: './contentScript.bundle.js',
+        });
+        const isScriptExists = await contentScriptExist(tabId, currentFrameId);
+
+        if (isScriptExists) {
+          resolve(true);
+        } else {
+          setTimeout(tryExecute, 1000);
+        }
+      } catch (error) {
+        console.error(error);
+        setTimeout(tryExecute, 1000);
+      }
+    })();
+  });
+}

+ 10 - 0
src/background/workflowEngine/worker.js

@@ -2,6 +2,7 @@ import browser from 'webextension-polyfill';
 import { toCamelCase, sleep, objectHasKey, isObject } from '@/utils/helper';
 import { tasks } from '@/utils/shared';
 import referenceData from '@/utils/referenceData';
+import injectContentScript from './injectContentScript';
 import { convertData, waitTabLoaded, getBlockConnection } from './helper';
 
 class Worker {
@@ -335,6 +336,15 @@ class Worker {
     } catch (error) {
       console.error(error);
       if (error.message?.startsWith('Could not establish connection')) {
+        const isScriptInjected = await injectContentScript(
+          this.activeTab.id,
+          this.activeTab.frameId
+        );
+
+        if (isScriptInjected) {
+          const result = await this._sendMessageToTab(payload, options);
+          return result;
+        }
         error.message = 'Could not establish connection to the active tab';
       } else if (error.message?.startsWith('No tab')) {
         error.message = 'active-tab-removed';

+ 1 - 1
src/composable/shortcut.js

@@ -77,7 +77,7 @@ export function getReadableShortcut(str) {
       mac: '⌘',
     },
   };
-  const regex = new RegExp('option|mod', 'g');
+  const regex = /option|mod/g;
   const replacedStr = str.replace(regex, (match) => {
     return list[match][os];
   });

+ 1 - 1
src/content/blocksHandler/handlerTakeScreenshot.js

@@ -170,7 +170,7 @@ export default async function ({ tabId, options, data: { type, selector } }) {
     scrollPosition = newScrollPos;
     scrollableElement.scrollTo(0, newScrollPos);
 
-    await new Promise((resolve) => setTimeout(resolve, 1000));
+    await sleep(1000);
   }
 
   style.remove();

+ 4 - 1
src/newtab/pages/workflows/[id].vue

@@ -114,7 +114,10 @@
         </workflow-builder>
         <div v-else class="container pb-4 mt-24 px-4">
           <template v-if="activeTab === 'logs'">
-            <div v-if="!logs || logs.length === 0" class="text-center">
+            <div
+              v-if="(!logs || logs.length === 0) && workflowState.length === 0"
+              class="text-center"
+            >
               <img
                 src="@/assets/svg/files-and-folder.svg"
                 class="mx-auto max-w-sm"

+ 2 - 1
src/utils/handleFormElement.js

@@ -1,3 +1,4 @@
+import { sleep } from '@/utils/helper';
 import { keyDefinitions } from '@/utils/USKeyboardLayout';
 import simulateEvent from './simulateEvent';
 
@@ -66,7 +67,7 @@ async function inputText({ data, element, isEditable }) {
         isEditable,
       });
 
-      await new Promise((r) => setTimeout(r, data.delay));
+      await sleep(data.delay);
     }
   } else {
     element[elementKey] += data.value;

+ 5 - 1
src/utils/helper.js

@@ -21,7 +21,11 @@ export function visibleInViewport(element) {
 }
 
 export function sleep(timeout = 500) {
-  return new Promise((resolve) => setTimeout(resolve, timeout));
+  return new Promise((resolve) => {
+    setTimeout(() => {
+      resolve();
+    }, timeout);
+  });
 }
 
 export function findTriggerBlock(drawflow = {}) {