Browse Source

fix: conditions block not working

Ahmad Kholid 2 years ago
parent
commit
6841ba6dc5

+ 0 - 50
src/content/blocksHandler/handlerConditions.js

@@ -1,9 +1,5 @@
-import { customAlphabet } from 'nanoid/non-secure';
 import { visibleInViewport, isXPath } from '@/utils/helper';
 import handleSelector from '../handleSelector';
-import { automaRefDataStr } from '../utils';
-
-const nanoid = customAlphabet('1234567890abcdef', 5);
 
 async function handleConditionElement({ data, type, id, frameSelector }) {
   const selectorType = isXPath(data.selector) ? 'xpath' : 'cssSelector';
@@ -52,49 +48,6 @@ async function handleConditionElement({ data, type, id, frameSelector }) {
 
   return elementActions[actionType](data);
 }
-function injectJsCode({ data, refData }) {
-  return new Promise((resolve, reject) => {
-    const varName = `automa${nanoid()}`;
-
-    const scriptEl = document.createElement('script');
-    scriptEl.textContent = `
-      (async () => {
-        const ${varName} = ${JSON.stringify(refData)};
-        ${automaRefDataStr(varName)}
-        try {
-          ${data.code}
-        } catch (error) {
-          return {
-            $isError: true,
-            message: error.message,
-          }
-        }
-      })()
-        .then((detail) => {
-          window.dispatchEvent(new CustomEvent('__automa-condition-code__', { detail }));
-        });
-    `;
-
-    document.body.appendChild(scriptEl);
-
-    const handleAutomaEvent = ({ detail }) => {
-      scriptEl.remove();
-      window.removeEventListener(
-        '__automa-condition-code__',
-        handleAutomaEvent
-      );
-
-      if (detail.$isError) {
-        reject(new Error(detail.message));
-        return;
-      }
-
-      resolve(detail);
-    };
-
-    window.addEventListener('__automa-condition-code__', handleAutomaEvent);
-  });
-}
 
 export default async function (data) {
   let result = null;
@@ -102,9 +55,6 @@ export default async function (data) {
   if (data.type.startsWith('element')) {
     result = await handleConditionElement(data);
   }
-  if (data.type.startsWith('code')) {
-    result = await injectJsCode(data);
-  }
 
   return result;
 }

+ 2 - 3
src/content/index.js

@@ -245,7 +245,7 @@ function messageListener({ data, source }) {
 })();
 
 // Auto install only works on Chrome
-async function autoInstall() {
+(async function autoInstall() {
   const link = window.location.href;
   if (/.+\.automa\.json$/.test(link)) {
     const accept = window.confirm(
@@ -277,5 +277,4 @@ async function autoInstall() {
 
     alert('Workflow installed');
   }
-}
-autoInstall();
+})();

+ 67 - 1
src/newtab/utils/workflowEngine/blocksHandler/handlerConditions.js

@@ -1,6 +1,11 @@
+import { customAlphabet } from 'nanoid/non-secure';
+import browser from 'webextension-polyfill';
 import compareBlockValue from '@/utils/compareBlockValue';
 import mustacheReplacer from '@/utils/referenceData/mustacheReplacer';
 import testConditions from '@/utils/testConditions';
+import { automaRefDataStr } from '../helper';
+
+const nanoid = customAlphabet('1234567890abcdef', 5);
 
 function checkConditions(data, conditionOptions) {
   return new Promise((resolve, reject) => {
@@ -40,6 +45,66 @@ function checkConditions(data, conditionOptions) {
     testAllConditions();
   });
 }
+function checkCodeCondition(activeTab, payload) {
+  const variableId = nanoid();
+
+  return browser.scripting
+    .executeScript({
+      world: 'MAIN',
+      args: [payload, variableId, automaRefDataStr(variableId)],
+      target: {
+        tabId: activeTab.id,
+        frameIds: [activeTab.frameId || 0],
+      },
+      func: ({ data, refData }, varId, refDataScript) => {
+        return new Promise((resolve, reject) => {
+          const varName = `automa${varId}`;
+
+          const scriptEl = document.createElement('script');
+          scriptEl.textContent = `
+          (async () => {
+            const ${varName} = ${JSON.stringify(refData)};
+            ${refDataScript}
+            try {
+              ${data.code}
+            } catch (error) {
+              return {
+                $isError: true,
+                message: error.message,
+              }
+            }
+          })()
+            .then((detail) => {
+              window.dispatchEvent(new CustomEvent('__automa-condition-code__', { detail }));
+            });
+        `;
+
+          document.documentElement.appendChild(scriptEl);
+
+          const handleAutomaEvent = ({ detail }) => {
+            scriptEl.remove();
+            window.removeEventListener(
+              '__automa-condition-code__',
+              handleAutomaEvent
+            );
+
+            if (detail.$isError) {
+              reject(new Error(detail.message));
+              return;
+            }
+
+            resolve(detail);
+          };
+
+          window.addEventListener(
+            '__automa-condition-code__',
+            handleAutomaEvent
+          );
+        });
+      },
+    })
+    .then(([result]) => result.result);
+}
 
 async function conditions({ data, id }, { prevBlockData, refData }) {
   if (data.conditions.length === 0) {
@@ -59,7 +124,8 @@ async function conditions({ data, id }, { prevBlockData, refData }) {
   if (condition && condition.conditions) {
     const conditionPayload = {
       refData,
-      activeTab: this.activeTab.id,
+      checkCodeCondition: (payload) =>
+        checkCodeCondition(this.activeTab, payload),
       sendMessage: (payload) =>
         this._sendMessageToTab({ ...payload.data, label: 'conditions', id }),
     };

+ 10 - 2
src/utils/testConditions.js

@@ -60,13 +60,21 @@ export default async function (conditionsArr, workflowData) {
 
     if (type === 'value') return copyData.value;
 
-    if (type.startsWith('element') || type.startsWith('code')) {
+    if (type.startsWith('code')) {
+      const conditionValue = await workflowData.checkCodeCondition({
+        data: copyData,
+        refData: workflowData.refData,
+      });
+
+      return conditionValue;
+    }
+
+    if (type.startsWith('element')) {
       const conditionValue = await workflowData.sendMessage({
         type: 'condition-builder',
         data: {
           type,
           data: copyData,
-          refData: workflowData.refData,
         },
       });