forked from AutomaApp/automa
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconditionCode.js
More file actions
107 lines (93 loc) · 2.94 KB
/
conditionCode.js
File metadata and controls
107 lines (93 loc) · 2.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { customAlphabet } from 'nanoid/non-secure';
import browser from 'webextension-polyfill';
import { automaRefDataStr, messageSandbox, checkCSPAndInject } from '../helper';
const nanoid = customAlphabet('1234567890abcdef', 5);
const isMV2 = browser.runtime.getManifest().manifest_version === 2;
export default async function (activeTab, payload) {
const variableId = `automa${nanoid()}`;
if (
!payload.data.context ||
payload.data.context === 'website' ||
!payload.isPopup
) {
if (!activeTab.id) throw new Error('no-tab');
const refDataScriptStr = automaRefDataStr(variableId);
if (!isMV2) {
const result = await checkCSPAndInject(
{
target: { tabId: activeTab.id },
debugMode: payload.debugMode,
},
() => {
return `
(async () => {
const ${variableId} = ${JSON.stringify(payload.refData)};
${refDataScriptStr}
try {
${payload.data.code}
} catch (error) {
return {
$isError: true,
message: error.message,
}
}
})();
`;
}
);
if (result.isBlocked) return result.value;
}
const [{ result }] = await browser.scripting.executeScript({
world: 'MAIN',
args: [payload, variableId, refDataScriptStr],
target: {
tabId: activeTab.id,
frameIds: [activeTab.frameId || 0],
},
func: ({ data, refData }, varId, refDataScript) => {
return new Promise((resolve, reject) => {
const varName = 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
);
});
},
});
return result;
}
const result = await messageSandbox('conditionCode', payload);
if (result && result.$isError) throw new Error(result.message);
return result;
}