-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
376 lines (351 loc) · 15.9 KB
/
content.js
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log('Received message:', message);
if (message.type === 'retrieveDocumentLanguage') {
console.log("Language: ", document.documentElement.lang);
sendResponse({ type: 'DOCUMENT_LANGUAGE', language: document.documentElement.lang});
} else if (message.type === 'retrieveCurrentUrl') {
console.log("URL: ", window.location.href);
sendResponse({ type: 'CURRENT_URL', url: window.location.href});
} else if (message.type === 'processingStarted') {
console.log('Processing started');
console.log("Language: ", document.documentElement.lang);
sendResponse({ type: 'ACTION_COMPLETED'});
} else if (message.type === 'processingFinished') {
console.log('Processing finished');
sendResponse({ type: 'PROCESSING_COMPLETED'});
} else if (message.type === 'conditionalSkip') {
let element = document.querySelector(message.selector);
let found = false;
if (element && message.text) {
const regex = new RegExp(message.text);
const elements = document.querySelectorAll(message.selector);
for (let el of elements) {
if (regex.test(el.textContent.trim())) {
found = true;
break;
}
}
} else {
found = !!element;
}
const newState = found ? message.stateIfFound : message.stateIfNotFound;
console.log(`Conditional skip action ${found ? 'found' : 'not found'} element for selector: ${message.selector}`);
sendResponse({ type: 'GOTO_STATE', state: newState });
} else if (message.type === 'click') {
const element = document.querySelector(message.selector);
if (element) {
element.click();
console.log('Click action completed:', message.description);
sendResponse({ type: 'ACTION_COMPLETED' });
} else {
console.error('Click action failed:', message.description);
sendResponse({ type: 'ACTION_FAILED', description: message.description });
}
} else if (message.type === 'retrieve') {
const elements = document.querySelectorAll(message.selector);
let found = false;
let value = null;
elements.forEach(element => {
if (element.value !== undefined) {
if (message.pattern) {
const regex = new RegExp(message.pattern);
if (regex.test(element.value)) {
value = element.value;
found = true;
}
} else {
value = element.value;
found = true;
}
}
if (found) {
console.log('Retrieve action completed:', message.description, ' (', message.key, '/', value, ')');
sendResponse({
type: 'RETRIEVE_COMPLETED',
key: message.key,
value: value
});
return;
}
});
if (!found) {
console.error('Retrieve action failed:', message.description);
sendResponse({ type: 'ACTION_FAILED', description: message.description });
}
} else if (message.type === 'wait') {
const { selector, timeout, retries, description, textContent } = message;
if (textContent) {
waitForElementWithText(selector, textContent, timeout, retries)
.then(() => {
console.log('Wait action completed:', description);
sendResponse({ type: 'ACTION_COMPLETED' });
})
.catch(() => {
console.error('Wait action failed:', description);
sendResponse({ type: 'ACTION_FAILED', description: description });
});
} else {
waitForElement(selector, timeout, retries)
.then(() => {
console.log('Wait action completed:', description);
sendResponse({ type: 'ACTION_COMPLETED' });
})
.catch(() => {
console.error('Wait action failed:', description);
sendResponse({ type: 'ACTION_FAILED', description: description });
});
}
} else if (message.type === 'waitForUrl') {
const { urlPattern, timeout, retries, description } = message;
waitForUrl(urlPattern, timeout, retries)
.then(() => {
console.log('Wait for URL action completed:', description);
sendResponse({ type: 'ACTION_COMPLETED' });
})
.catch(() => {
console.error('Wait for URL action failed:', description);
sendResponse({ type: 'ACTION_FAILED', description: description });
});
} else if (message.type === 'nestedClick') {
const parentElement = document.querySelector(message.parentSelector);
if (parentElement) {
const childElement = parentElement.querySelector(message.childSelector);
if (childElement) {
childElement.click();
console.log('Nested click action completed:', message.description);
sendResponse({ type: 'ACTION_COMPLETED' });
} else {
console.error('Nested click action failed:', message.description);
sendResponse({ type: 'ACTION_FAILED', description: message.description });
}
} else {
console.error('Nested click action failed:', message.description);
sendResponse({ type: 'ACTION_FAILED', description: message.description });
}
} else if (message.type === 'clickByText') {
const elements = document.getElementsByTagName(message.tag);
const regex = new RegExp(message.text);
let found = false;
for (let element of elements) {
if (regex.test(element.textContent.trim())) {
element.click();
found = true;
console.log('Click by text action completed:', message.description);
sendResponse({ type: 'ACTION_COMPLETED' });
break;
}
}
if (!found) {
console.error('Click by text action failed:', message.description);
sendResponse({ type: 'ACTION_FAILED', description: message.description });
}
} else if (message.type === 'fillValue') {
const element = document.activeElement;
if (element && (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || (element.tagName === 'DIV' && element.role === 'textbox'))) {
simulateTyping(element, message.value)
.then(() => {
console.log('Fill value action completed');
sendResponse({ type: 'ACTION_COMPLETED' });
})
.catch((error) => {
console.error('Fill value action failed:', error);
sendResponse({ type: 'ACTION_FAILED', description: error });
});
} else {
console.error('Fill value action failed: No active input, textarea, or div with role textbox element');
sendResponse({ type: 'ACTION_FAILED', description: 'No active input, textarea, or div with role textbox element' });
}
} else if (message.type === 'fillChildPValue') {
const activeElement = document.activeElement;
if (activeElement) {
let pElement = activeElement.querySelector('p');
if (!pElement) {
pElement = document.createElement('p');
activeElement.appendChild(pElement);
}
// Clear the <p> element using innerHTML
pElement.innerHTML = '';
console.log('Children after clearing with innerHTML:', pElement.childNodes); // Debugging log
// Set the text content for contenteditable
simulateTypingSimple(pElement, message.value);
console.log('pElement innerHTML after setting text:', pElement.innerHTML); // Debugging log
console.log('Fill value in child <p> action completed:', message.value);
sendResponse({ type: 'ACTION_COMPLETED' });
} else {
console.error('Fill value in child <p> action failed: No active element');
sendResponse({ type: 'ACTION_FAILED', description: 'No active element' });
}
} else if (message.type === 'typeText') {
const element = document.activeElement;
if (element && (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || (element.tagName === 'DIV' && element.role === 'textbox'))) {
simulateTyping(element, message.text)
.then(() => {
console.log('Type text action completed');
sendResponse({ type: 'ACTION_COMPLETED' });
})
.catch((error) => {
console.error('Type text action failed:', error);
sendResponse({ type: 'ACTION_FAILED', description: error });
});
} else {
console.error('Type text action failed: No active input, textarea, or div with role textbox element');
sendResponse({ type: 'ACTION_FAILED', description: 'No active input, textarea, or div with role textbox element' });
}
} else if (message.type === 'moveToNextElement') {
const currentElement = document.activeElement;
if (currentElement) {
const nextElement = currentElement.nextElementSibling;
if (nextElement && nextElement.tabIndex !== -1) {
nextElement.focus();
console.log('Move to next element action completed');
sendResponse({ type: 'ACTION_COMPLETED' });
} else {
console.error('Move to next element action failed: No next focusable element');
sendResponse({ type: 'ACTION_FAILED', description: 'No next focusable element' });
}
} else {
console.error('Move to next element action failed: No active element');
sendResponse({ type: 'ACTION_FAILED', description: 'No active element' });
}
} else if (message.type === 'focusElement') {
const element = document.querySelector(message.selector);
if (element) {
element.click();
element.focus();
if (element.isContentEditable && element.firstChild) {
let range = document.createRange();
let sel = window.getSelection();
range.setStart(element.firstChild, 0);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
if (element.isContentEditable) {
element.firstChild.click();
element.innerHTML = element.innerHTML; // Forces the browser to render the cursor
}
console.log('Focus element action completed:', message.description);
sendResponse({ type: 'ACTION_COMPLETED' });
} else {
console.error('Focus element action failed:', message.description);
sendResponse({ type: 'ACTION_FAILED', description: message.description });
}
} else if (message.type === 'storeValue') {
chrome.storage.local.set({ [message.key]: message.value }, function() {
console.log('Stored value in Chrome storage:', message.key, message.value);
sendResponse({ type: 'ACTION_COMPLETED' });
});
} else if (message.type === 'eraseValue') {
chrome.storage.local.remove(message.key, function() {
console.log('Erased value from Chrome storage:', message.key);
sendResponse({ type: 'ACTION_COMPLETED' });
});
} else if (message.type === 'log') {
console.log('Log action:', message.message);
sendResponse({ type: 'ACTION_COMPLETED', message: message.message });
} else {
console.log('Unknown message type:', message.type);
}
// Ensure the response is sent asynchronously
return true;
});
function waitForElement(selector, timeout, retries) {
return new Promise((resolve, reject) => {
const interval = setInterval(() => {
if (document.querySelector(selector)) {
clearInterval(interval);
resolve();
} else if (retries <= 0) {
clearInterval(interval);
reject();
}
retries--;
}, timeout);
});
}
function waitForElementWithText(tag, textPattern, timeout, retries) {
return new Promise((resolve, reject) => {
const regex = new RegExp(textPattern);
const interval = setInterval(() => {
const elements = document.getElementsByTagName(tag);
let found = false;
for (let element of elements) {
// console.log("Test", element.textContent.trim());
if (regex.test(element.textContent.trim())) {
clearInterval(interval);
resolve();
found = true;
break;
}
}
if (!found && retries <= 0) {
clearInterval(interval);
reject();
}
retries--;
}, timeout);
});
}
function waitForUrl(urlPattern, timeout, retries) {
return new Promise((resolve, reject) => {
const regex = new RegExp(urlPattern);
const interval = setInterval(() => {
if (window.location.href.match(regex)) {
clearInterval(interval);
resolve();
} else if (retries <= 0) {
clearInterval(interval);
reject();
}
retries--;
}, timeout);
});
}
function simulateTyping(element, text) {
return new Promise((resolve) => {
let index = 0;
function typeCharacter() {
if (index < text.length) {
element.click();
const char = text.charAt(index);
const event = new Event('input', {
bubbles: true,
cancelable: true,
});
const keyDownEvent = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, key: char });
const keyPressEvent = new KeyboardEvent('keypress', { bubbles: true, cancelable: true, key: char });
const inputEvent = new InputEvent('input', { bubbles: true, cancelable: true, data: char });
const keyUpEvent = new KeyboardEvent('keyup', { bubbles: true, cancelable: true, key: char });
element.dispatchEvent(keyDownEvent);
element.dispatchEvent(keyPressEvent);
element.value += char;
element.dispatchEvent(inputEvent);
element.dispatchEvent(keyUpEvent);
// element.dispatchEvent(event);
index++;
element.click();
setTimeout(typeCharacter, 5); // Adjust typing speed if needed
} else {
resolve();
}
}
typeCharacter();
});
}
function simulateTypingSimple(element, text) {
document.execCommand("insertText", false, text);
// Dispatch a change event at the end
const inputEvent = new InputEvent('input', { bubbles: true, cancelable: true});
element.dispatchEvent(inputEvent);
const changeEvent = new Event('change', { bubbles: true, cancelable: true });
element.dispatchEvent(changeEvent);
}
function simulateTab() {
const currentElement = document.activeElement;
const nextElement = currentElement.nextElementSibling;
if (nextElement && nextElement.tabIndex !== -1) {
nextElement.focus();
} else {
console.error('Simulate tab action failed: No next focusable element');
}
}